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/main/kotlin/se/saidaspen/aoc/aoc2018/Day06.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2018 import se.saidaspen.aoc.util.* import kotlin.math.abs fun main() { Day06.run() } object Day06 : Day(2018, 6) { override fun part1(): Any { val grid = Grid(".") val coords = input.lines().map { ints(it) }.map { P(it[0], it[1]) }.toList() for ((i, p) in coords.withIndex()) { grid[p] = i.toString() } for (r in 0 until grid.height){ for (c in 0 until grid.width) { val distances = coords.map { P(it, manhattanDist(c, r, it.first, it.second)) }.sortedBy { it.second } val closest = if (distances[0].second == distances[1].second) "." else coords.indexOf(distances[0].first).toString() grid[c, r] = closest } } val largestArea = (coords.indices).maxOf { areaOf(it, grid) } for ((i, p) in coords.withIndex()) { grid[p] = i.toString() } return largestArea } override fun part2(): Any { val grid = Grid(".") val coords = input.lines().map { ints(it) }.map { P(it[0], it[1]) }.toList() for ((i, p) in coords.withIndex()) { grid[p] = i.toString() } var sum = 0 for (r in 0 until grid.height){ for (c in 0 until grid.width) { val distances = coords.sumOf { manhattanDist(c, r, it.first, it.second) } if (distances < 10_000){ sum++ } } } return sum } private fun areaOf(v: Int, grid: Grid<String>): Int { val points = grid.points().filter { it.second == v.toString() } val coords = points.map { it.first } return if (coords.map { it.first }.any { it == 0 || it == grid.height -1 } || coords.map { it.second }.any { it == 0 || it == grid.width -1 }) 0 else points.size } private fun manhattanDist(x1: Int, y1: Int, x2: Int, y2: Int): Int { return abs(x1-x2) + abs(y1-y2) } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,036
adventofkotlin
MIT License
src/main/kotlin/days/y2023/day05/Day05.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day05 import util.InputReader typealias Seed = Long typealias PuzzleInput = String class Day05(val input: PuzzleInput) { val seeds = parseSeeds(input) val seedRanges = parseSeedRanges(input) val remappers = parseRemappers(input) fun partOne() = seeds.minOf { mapSeed(it) } fun partTwo(): Long { println("Checking ${seedRangeSize()} seeds") return seedRanges.minOf { range -> range.minOf { mapSeed(it) } } } fun seedRangeSize() = seedRanges.sumOf { it.last - it.first }.let { it to "${(it / 1_000_000L)} million" } var i = 0L fun mapSeed(seed: Seed): Seed { i++ if (i % 1_000_000 == 0L) { println("i: ${i / 1_000_000} million of ${seedRangeSize().second} seeds") } var result: Seed = seed var nextRemapper: Remapper? = remappers.find { it.from == "seed" }!! while (nextRemapper != null) { result = nextRemapper.map(result) nextRemapper = remappers.find { it.from == nextRemapper!!.to } } return result } } data class Remapper(val from: String, val to: String, val ranges: Map<LongRange, LongRange>) { fun map(input: Long): Long { val mapEntry = ranges.entries.firstOrNull { it.value.contains(input) } if (mapEntry == null) { return input } val (destination, source) = mapEntry val offset = input - source.first return destination.first + offset } } private fun parseRemappers(input: PuzzleInput): List<Remapper> { val chunks = input.trim().lines().drop(2).joinToString("\n").split("\n\n") return chunks.map { chunk -> val (header, rest) = chunk.split("\n", limit = 2) val restLines = rest.lines() val (from, _, to) = header.split(" ")[0].split("-") val pairs = restLines.map { val (destinationBegin, sourceBegin, length) = it.split(" ").map { it.toLong() } (destinationBegin until destinationBegin + length) to (sourceBegin until sourceBegin + length) } Remapper(from, to, pairs.toMap()) } } private fun parseSeeds(input: PuzzleInput): List<Long> = input.trim().lines().first().split("seeds: ")[1].run { split(" ").map { it.toLong() } } // seeds: 79 14 55 13 private fun parseSeedRanges(input: PuzzleInput): List<LongRange> = input.trim().lines().first().split("seeds: ")[1] .run { split(" ").map { it.toLong() } } .chunked(2) .map { (start, length) -> start until start + length } fun main() { val year = 2023 val day = 5 val exampleInput: PuzzleInput = InputReader.getExample(year, day) val puzzleInput: PuzzleInput = InputReader.getPuzzle(year, day) fun partOne(input: PuzzleInput): Long = Day05(input).partOne() fun partTwo(input: PuzzleInput): Long = Day05(input).partTwo() /* Seed number 79 corresponds to soil number 81. Seed number 14 corresponds to soil number 14. Seed number 55 corresponds to soil number 57. Seed number 13 corresponds to soil number 13. */ // val seedSoilRemapper = parseRemappers(exampleInput).find { it.from == "seed" && it.to == "soil" }!! // println("Seed number 79 corresponds to soil number ${seedSoilRemapper.map(79L)}") // println("Seed number 14 corresponds to soil number ${seedSoilRemapper.map(14L)}") // println("Seed number 55 corresponds to soil number ${seedSoilRemapper.map(55L)}") // println("Seed number 13 corresponds to soil number ${seedSoilRemapper.map(13L)}") // println("Seed number 53 corresponds to soil number ${seedSoilRemapper.map(53L)}") // println("Seed 79 ${Day05(exampleInput).mapSeed(79L)}") // println("Seed 14 ${Day05(exampleInput).mapSeed(14L)}") // println("Seed 55 ${Day05(exampleInput).mapSeed(55L)}") // println("Seed 13 ${Day05(exampleInput).mapSeed(13L)}") // println(Day05(exampleInput).seedRanges) println("Example 1: ${partOne(exampleInput)}") println("Part 1: ${partOne(puzzleInput)}") println("Example 2: ${partTwo(exampleInput)}") println("Part 2: ${partTwo(puzzleInput)}") }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
4,154
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/design/SearchAutocompleteSystem.kt
e-freiman
471,473,372
false
{"Kotlin": 78010}
package design class AutocompleteSystem(sentences: Array<String>, times: IntArray) { private class TrieNode { var leafTimes = 0 val children = mutableMapOf<Char, TrieNode>() } private val trieRoot = TrieNode() private var currentNode: TrieNode private val prefix = StringBuilder() init { for (i in sentences.indices) { var cur = trieRoot for (c in sentences[i]) { if (c !in cur.children) { cur.children[c] = TrieNode() } cur = cur.children[c]!! } cur.leafTimes = times[i] } currentNode = trieRoot } private fun dfsTraverse(prefix: StringBuilder, currentNode: TrieNode, sentencesList: MutableList<Pair<String, Int>>) { if (currentNode.leafTimes > 0) { sentencesList.add(prefix.toString() to currentNode.leafTimes) } for (entry in currentNode.children.entries.iterator()) { prefix.append(entry.key) dfsTraverse(prefix, entry.value, sentencesList) prefix.deleteCharAt(prefix.lastIndex) } } fun input(c: Char): List<String> { if (c == '#') { currentNode.leafTimes++ currentNode = trieRoot prefix.delete(0, prefix.length) return listOf<String>() } if (c !in currentNode.children) { currentNode.children[c] = TrieNode() } currentNode = currentNode.children[c]!! prefix.append(c) val sentencesList = mutableListOf<Pair<String, Int>>() dfsTraverse(prefix, currentNode, sentencesList) sentencesList.sortWith(object: Comparator<Pair<String, Int>> { override fun compare(a: Pair<String, Int>, b: Pair<String, Int>): Int = when { a.second != b.second -> -a.second + b.second else -> a.first.compareTo(b.first) } }) return if (sentencesList.size < 3) { sentencesList.map {it.first} } else { sentencesList.subList(0, 3).map {it.first} } } } fun main() { val obj = AutocompleteSystem(arrayOf("i love you", "island", "iroman", "i love leetcode"), intArrayOf(5, 3, 2, 2)) println(obj.input('i')) // return ["i love you", "island", "i love leetcode"]. There are four sentences that have prefix "i". Among them, "ironman" and "i love leetcode" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode" should be in front of "ironman". Also we only need to output top 3 hot sentences, so "ironman" will be ignored. println(obj.input(' ')) // return ["i love you", "i love leetcode"]. There are only two sentences that have prefix "i ". println(obj.input('a')) // return []. There are no sentences that have prefix "i a". println(obj.input('#')) // return []. The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search. }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
3,094
LeetcodeGoogleInterview
Apache License 2.0
src/Day04.kt
davidkna
572,439,882
false
{"Kotlin": 79526}
fun main() { fun Boolean.toInt() = if (this) 1 else 0 fun part1(input: List<String>): Int { return input.filter { return@filter it.isNotEmpty() }.sumOf { val (first, second) = it.split(",") val (x0, y0) = first.split("-").map { n -> n.toInt() } val (x1, y1) = second.split("-").map { n -> n.toInt() } ( ( (x0..y0).contains(x1) && (x0..y0).contains(y1) ) || ( (x1..y1).contains(x0) && (x1..y1).contains(y0) ) ).toInt() } } fun part2(input: List<String>): Int { return input.filter { return@filter it.isNotEmpty() }.sumOf { val (first, second) = it.split(",") val (x0, y0) = first.split("-").map { n -> n.toInt() } val (x1, y1) = second.split("-").map { n -> n.toInt() } ( (x0..y0).contains(x1) || (x0..y0).contains(y1) || (x1..y1).contains(x0) || (x1..y1).contains(y0) ).toInt() } } 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
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
1,419
aoc-2022
Apache License 2.0
2022/src/main/kotlin/Day08.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
object Day08 { fun part1(input: String): Int { val trees = input.splitNewlines().map { it.toIntList() } val size = trees.size // Assume square input return trees.indices.sumOf { y -> trees[y].indices.count { x -> val tree = trees[y][x] return@count (0 until x).all { tree > trees[y][it] } || (x + 1 until size).all { tree > trees[y][it] } || (0 until y).all { tree > trees[it][x] } || (y + 1 until size).all { tree > trees[it][x] } } } } fun part2(input: String): Int { val trees = input.splitNewlines().map { it.toIntList() } val size = trees.size // Assume square input return trees.indices.maxOf { y -> trees[y].indices.maxOf { x -> val tree = trees[y][x] return@maxOf (x - 1 downTo 0).asSequence().map { trees[y][it] }.viewingDistance(tree) * (x + 1 until size).asSequence().map { trees[y][it] }.viewingDistance(tree) * (y - 1 downTo 0).asSequence().map { trees[it][x] }.viewingDistance(tree) * (y + 1 until size).asSequence().map { trees[it][x] }.viewingDistance(tree) } } } private fun Sequence<Int>.viewingDistance(tree: Int): Int { var counter = 0 for (other in this) { if (tree <= other) { return counter + 1 } counter++ } return counter } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
1,370
advent-of-code
MIT License
y2020/src/main/kotlin/adventofcode/y2020/Day21.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution fun main() = Day21.solve() object Day21 : AdventSolution(2020, 21, "Allergen Assessment") { override fun solvePartOne(input: String): Int { val entries = input.lines().map(::parseEntry) val allergens = findAllergens(entries).values.reduce(Set<String>::union) return entries.flatMap { it.first.toList() }.count { it !in allergens } } override fun solvePartTwo(input: String): Any { val entries = input.lines().map(::parseEntry) var allergenCandidateMap = findAllergens(entries) val map: Map<String, String> = buildMap { while (allergenCandidateMap.isNotEmpty()) { val (allergen, ingredient) = allergenCandidateMap.entries.first { it.value.size == 1 } this[allergen] = ingredient.single() allergenCandidateMap = allergenCandidateMap.mapValues { it.value - ingredient }.filterValues { it.isNotEmpty() } } } return map.toSortedMap().values.joinToString(",") } private fun parseEntry(input: String): Pair<Set<String>, List<String>> { val ingredients = input.substringBefore(" (").split(" ").toSet() val allergens = input.substringAfter("(contains ").substringBefore(")").split(", ") return ingredients to allergens } private fun findAllergens(entries: List<Pair<Set<String>, List<String>>>) = entries .flatMap { (ingredients, allergens) -> allergens.map { it to ingredients } } .groupBy({ it.first }, { it.second }) .mapValues { it.value.reduce(Set<String>::intersect) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,678
advent-of-code
MIT License
src/Day17.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
import java.util.PriorityQueue fun Direction.isOpposite(d: Direction) = when (this) { Direction.UP -> d == Direction.DOWN Direction.DOWN -> d == Direction.UP Direction.LEFT -> d == Direction.RIGHT Direction.RIGHT -> d == Direction.LEFT } fun getDirection(rc1: RowCol, rc2: RowCol): Direction { val (i1, j1) = rc1 val (i2, j2) = rc2 return when { i1 == i2 && j1 < j2 -> Direction.RIGHT i1 == i2 && j1 > j2 -> Direction.LEFT i1 < i2 && j1 == j2 -> Direction.DOWN i1 > i2 && j1 == j2 -> Direction.UP else -> error("asdsa") } } data class Position( val rc: RowCol, val lastMoves: List<Direction> = listOf() ) fun MutableInput<Long>.isEnd(curr: Position): Boolean { val (i, j) = curr.rc return (i == this.size - 1 && j == this[0].size - 1) } typealias CruciblePath = MutableMap<Position, Long> fun canMoveInDirection1(curr: Position, dir: Direction, maxInDirection: Int): Boolean { val isOpposite = curr.lastMoves.lastOrNull()?.isOpposite(dir) ?: false val maxNotReached = curr.lastMoves.count { it == dir } < maxInDirection return !isOpposite && maxNotReached } fun canMoveInDirection2(curr: Position, dir: Direction, maxInDirection: Int): Boolean { val canTurn = if (curr.lastMoves.isNotEmpty()) { val lastMove = curr.lastMoves.last() if (dir != lastMove) { curr.lastMoves.takeLast(4).count { it == lastMove } == 4 } else true } else true return canMoveInDirection1(curr, dir, maxInDirection) && canTurn } fun MutableInput<Long>.minHeatLossPath( maxInDirection: Int = 10, canMoveInDirection: (Position, Direction, Int) -> Boolean ): CruciblePath { val start = Position(rc = 0 to 0) val visited = mutableMapOf<Position, Long>().apply { put(start, 0L) } val q = PriorityQueue(compareBy<Position> { visited[it] ?: Long.MAX_VALUE }) //<CurrPosition>() q.add(start) while (q.isNotEmpty()) { val curr = q.poll() if (this.isEnd(curr)) continue this.adjacent(curr.rc) .map { it to getDirection(curr.rc, it) } .filter { (_, dir) -> canMoveInDirection(curr, dir, maxInDirection) } .forEach { (next, dir) -> val nextPos = Position(rc = next, lastMoves = (curr.lastMoves + dir).takeLast(maxInDirection)) val cost = visited[curr]!! + this.get(nextPos.rc) if (cost < (visited[nextPos] ?: Long.MAX_VALUE)) { visited[nextPos] = cost q.add(nextPos) } } } return visited } fun main() { fun part1(input: List<String>): Long { val grid = input.toMutableInput { it.digitToInt().toLong() } return grid.minHeatLossPath(3, ::canMoveInDirection1) .filterKeys { grid.isEnd(it) } .values.min() } fun part2(input: List<String>): Long { val grid = input.toMutableInput { it.digitToInt().toLong() } return grid.minHeatLossPath(10, ::canMoveInDirection2) .filterKeys { grid.isEnd(it) && it.lastMoves.takeLast(4).distinct().count() == 1 } .values.min() } val input = readInput("Day17") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
3,293
aoc-2023
Apache License 2.0
src/Day08.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
class Day08(private val lines: List<String>) { val column = lines.first().length - 1 val row = lines.size - 1 val treeSet = mutableSetOf<Tree>() fun part1(): Int { println("column $column") println("row $row") lookFromWest(lines) lookFromEast(lines) lookFromNorth(lines) lookFromSouth(lines) return treeSet.size } private fun lookFromWest(lines: List<String>) { for (r in 0..row) { var tallest = -1 val rowLine = lines[r] for (c in 0..column) { if (rowLine[c].code > tallest) { println("lookFromWest column $c row $r value ${rowLine[c].code}") tallest = rowLine[c].code treeSet.add(Tree(r, c)) } } } } private fun lookFromEast(lines: List<String>) { for (r in 0..row) { var tallest = -1 val rowLine = lines[r] for (c in column downTo 0) { if (rowLine[c].code > tallest) { println("lookFromEast column $c row $r value ${rowLine[c].code}") tallest = rowLine[c].code treeSet.add(Tree(r, c)) } } } } private fun lookFromNorth(lines: List<String>) { for (c in 0..column) { var tallest = -1 for (r in 0..row) { val tree = lines[r][c] if (tree.code > tallest) { tallest = tree.code treeSet.add(Tree(r,c)) println("lookFromNorth column $c row $r value $tallest") } } } } private fun lookFromSouth(lines: List<String>) { for (c in 0..column) { var tallest = -1 for (r in row downTo 0) { val tree = lines[r][c] if (tree.code > tallest) { tallest = tree.code treeSet.add(Tree(r,c)) println("lookFromSouth column $c row $r value $tallest") } } } } } class Day08Other(input: List<String>) { private val grid = input.map { it.toList().map(Char::digitToInt) } fun solvePart1() = traverse( score = { current, slice -> slice.all { it < current } }, combine = { directions -> if (directions.any { it }) 1 else 0 } ).sum() fun solvePart2() = traverse( score = { current, slice -> (slice.indexOfFirst { it >= current } + 1).takeIf { it != 0 } ?: slice.size }, combine = { it.reduce(Int::times) } ).max() private fun <T> traverse(score: (Int, List<Int>) -> T, combine: (List<T>) -> Int): List<Int> { return (grid.indices).flatMap { r -> (grid.indices).map { c -> val current = grid[r][c] val up = score(current, grid.slice(r - 1 downTo 0).map { it[c] }) val down = score(current, grid.slice(r + 1 until grid.size).map { it[c] }) val left = score(current, grid[r].slice(c - 1 downTo 0)) val right = score(current, grid[r].slice(c + 1 until grid.size)) combine(listOf(up, down, left, right)) } } } } fun main() { // val numbers = listOf(1, 1, 1) // val result = numbers.reduce { a: Int, b: Int -> a + b } // println("reduceResult=$result")//result=3 val numbers = listOf(1, 1, 1) val result = numbers.fold(StringBuilder()) { str: StringBuilder, i: Int -> str.append(i).append(" ") } println("foldResult=$result") // val day = "day8_input" // println(Day08Other(readInput(day)).solvePart2()) } data class Tree(val row: Int, val column: Int)
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
3,814
advent22
Apache License 2.0
src/Day02.kt
JohannesPtaszyk
573,129,811
false
{"Kotlin": 20483}
enum class Result(val id: String, val score: Int) { LOOSE(id = "X", score = 0), DRAW(id = "Y", score = 3), WIN(id = "Z", score = 6); companion object { fun forId(id: String): Result = values().first {it.id == id } } } enum class Shape(val score: Int, val encryptedValues: List<String>) { ROCK(score = 1, encryptedValues = listOf("A", "X")), PAPER(score = 2, encryptedValues = listOf("B", "Y")), SCISSORS(score = 3, encryptedValues = listOf("C", "Z")); fun playVs(opponent: Shape): Result { if (this == opponent) return Result.DRAW val isWin = when (this) { ROCK -> opponent == SCISSORS PAPER -> opponent == ROCK SCISSORS -> opponent == PAPER } return if (isWin) Result.WIN else Result.LOOSE } fun getOpponentForResult(expectedResult: Result): Shape = values().first { it.playVs(this) == expectedResult } companion object { fun forEncryptedValue(encryptedValue: String): Shape = values().first { it.encryptedValues.contains(encryptedValue) } } } fun main() { fun part1(input: List<String>): Int = input.sumOf { val (opponentValue, myValue) = it.split(" ") val opponentShape = Shape.forEncryptedValue(opponentValue) val myShape = Shape.forEncryptedValue(myValue) myShape.playVs(opponentShape).score + myShape.score } fun part2(input: List<String>): Int = input.sumOf { val (opponentValue, expectedResultId) = it.split(" ") val opponentShape = Shape.forEncryptedValue(opponentValue) val expectedResult = Result.forId(expectedResultId) val myShape = opponentShape.getOpponentForResult(expectedResult) myShape.score + expectedResult.score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
6f6209cacaf93230bfb55df5d91cf92305e8cd26
2,077
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day16/day16.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package day16 import main.utils.Edge import main.utils.Graph import main.utils.scanInt import utils.readFile import utils.readLines import kotlin.math.max fun main() { val test = readLines( """Valve AA has flow rate=0; tunnels lead to valves DD, II, BB Valve BB has flow rate=13; tunnels lead to valves CC, AA Valve CC has flow rate=2; tunnels lead to valves DD, BB Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE Valve EE has flow rate=3; tunnels lead to valves FF, DD Valve FF has flow rate=0; tunnels lead to valves EE, GG Valve GG has flow rate=0; tunnels lead to valves FF, HH Valve HH has flow rate=22; tunnel leads to valve GG Valve II has flow rate=0; tunnels lead to valves AA, JJ Valve JJ has flow rate=21; tunnel leads to valve II""" ) val input = readFile("day16") data class Cell(val name: String, val rate: Int) : Comparable<Cell> { var neighbours: Set<Pair<Cell, Int>> = emptySet() override fun compareTo(other: Cell): Int { return rate.compareTo(other.rate) } override fun toString(): String { return "($name, $rate, ${neighbours.map { it.first.name }})" } } fun loadCells(input: List<String>): List<Pair<Cell, List<String>>> { return input.map { line -> val (left, right) = line.split(";").map { it.trim() } val name = left.substringAfter("Valve ").substring(0..1) val rate = left.scanInt() val links = if (right.contains("tunnel leads to valve ")) listOf(right.substringAfter("tunnel leads to valve ").trim()) else right.substringAfter("valves ").split(",").map { it.trim() } Pair(Cell(name, rate), links) } } fun calcSolution(input: List<String>, minutes: Int, useElephant: Boolean): Int { val nodes = loadCells(input) val cells = nodes.map { it.first }.associateBy { it.name } val start = cells["AA"] ?: error("Cannot find AA") val edges: List<Edge<Cell>> = nodes.flatMap { node -> node.second.map { next -> cells[next] ?: error("Cannot find $next") }.map { Edge(node.first, it) } } val valves = cells.values.sortedByDescending { it.rate } val nonLeafNodes = cells.values.filter { it.rate > 0 }.sortedByDescending { it.rate } fun calculateDistances(): Map<Cell, Map<Cell, Int>> { val result = mutableMapOf<Cell, Map<Cell, Int>>() valves.forEach { start -> val graph = Graph(edges, true).apply { dijkstra(start) } val connections = nonLeafNodes.map { end -> end to (graph.findPath(end).lastOrNull() ?.second ?: Int.MAX_VALUE) .apply { println("Distance ${start.name} -> ${end.name} = $this") } }.toMap() result[start] = connections } return result } val distances = calculateDistances() var totalPressure = 0 fun visitValves(releasedPressure: Int, position: Cell, visited: List<Cell>, minute: Int, elephant: Boolean) { totalPressure = max(releasedPressure, totalPressure) println("minute $minute, position:${position.name}: visited:${visited.map { it.name }}: releasePressure=$releasedPressure: total $totalPressure") if (!elephant) { val possiblePressureRelease = (valves - visited) .zip((minutes - minute - 2 downTo 0 step 2)) { futureValve, futureMinute -> futureValve.rate * futureMinute }.sum() if (possiblePressureRelease + releasedPressure < totalPressure) return } if (!elephant) { val unvisited = (valves - visited) var index = 0 val remaining = minutes - minute downTo 0 step 2 val release = remaining.sumOf { (unvisited.getOrNull(index++)?.rate ?: 0) * it } if ((release + releasedPressure) < totalPressure) return } distances.getValue(position).forEach { (node, distance) -> val nextMinute = minute + distance + 1 if (nextMinute < minutes && !visited.contains(node)) { val candidatePressure = releasedPressure + ((minutes - nextMinute) * node.rate) visitValves(candidatePressure, node, visited + node, nextMinute, elephant) } } if (elephant) { visitValves(releasedPressure, start, visited, 0, false) } } println("Valves:") valves.forEach { println(it) } visitValves(0, start, listOf(), 0, useElephant) return totalPressure } fun part1() { val testResult = calcSolution(test, 30, false) println("Part 1 Answer = $testResult") check(testResult == 1651) { "Expected 1651 not $testResult" } val result = calcSolution(input, 30, false) println("Part 1 Answer = $result") check(result == 1559) { "Expected 1559 not $result" } } fun part2() { val testResult = calcSolution(test, 26, true) println("Part 1 Answer = $testResult") check(testResult == 1707) { "Expected 1707 not $testResult" } val result = calcSolution(input, 26, true) println("Part 1 Answer = $result") check(result == 2191) { "Expected 2191 not $result" } } println("Day - 16") part1() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
5,086
aoc-2022-in-kotlin
Apache License 2.0
src/day09.kt
skuhtic
572,645,300
false
{"Kotlin": 36109}
import kotlin.math.abs import kotlin.math.max fun main() { day09.execute(onlyTests = false, forceBothParts = true) } val day09 = object : Day<Int>(9, 88, 36) { override val testInput: InputData get() = """ R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20 """.trimIndent().lines() override fun part1(input: InputData): Int { val directions = input.map { line -> line.first() to line.drop(2).toInt() } var head = (0 to 0) var tail = (0 to 0) val visited = mutableSetOf(tail) directions.forEach { (dir, dist) -> repeat(dist) { head = head.moveOneInDirection(dir) if (!tail.isInRangeOfOne(head)) { tail = tail.moveOneTowards(head) // tail = visited.add(tail) } } } return visited.count() } override fun part2(input: InputData): Int { val directions = input.map { line -> line.first() to line.drop(2).toInt() } val knots = MutableList(10) { 0 to 0 } val visited = mutableSetOf(knots.last()) directions.forEach { (dir, dist) -> repeat(dist) {// Direction knots.indices.forEach move@{ kNo -> if (kNo == 0) { // Move head knots[kNo] = knots[kNo].moveOneInDirection(dir) } else { // rest follows if (knots[kNo].isInRangeOfOne(knots[kNo - 1])) return@move knots[kNo] = knots[kNo].moveOneTowards(knots[kNo - 1]) } // move done visited.add(knots.last()) } } // One direction done } // Directions done return visited.count() } fun Pair<Int, Int>.moveOneInDirection(direction: Char): Pair<Int, Int> = when (direction) { 'L' -> first - 1 to second 'R' -> first + 1 to second 'U' -> first to second + 1 'D' -> first to second - 1 else -> error("Invalid input, direction = $direction") } } fun Pair<Int, Int>.moveOneTowards(other: Pair<Int, Int>): Pair<Int, Int> { val x = if (other.first == first) 0 else if (other.first > first) 1 else -1 val y = if (other.second == second) 0 else if (other.second > second) 1 else -1 return first + x to second + y } fun Pair<Int, Int>.isInRangeOfOne(other: Pair<Int, Int>): Boolean { val max = max(abs(other.first - first), abs(other.second - second)) return max <= 1 }
0
Kotlin
0
0
8de2933df90259cf53c9cb190624d1fb18566868
2,655
aoc-2022
Apache License 2.0
lib/src/main/kotlin/com/bloidonia/advent/day20/Day20.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day20 import com.bloidonia.advent.readText data class Position(val x: Int, val y: Int) { operator fun plus(pos: Position) = Position(x + pos.x, y + pos.y) } class TrenchMap(val inverted: Boolean, val lookups: List<Int>, val settings: Set<Position>) { fun xRange(): IntRange = (settings.minOf { it.x } - 1)..(settings.maxOf { it.x } + 1) fun yRange(): IntRange = (settings.minOf { it.y } - 1)..(settings.maxOf { it.y } + 1) fun lookup(pos: Position, invert: Boolean) = (if (invert) Pair("0", "1") else Pair("1", "0")).let { lookups[((if (settings.contains(pos + Position(-1, -1))) it.first else it.second) + (if (settings.contains(pos + Position(0, -1))) it.first else it.second) + (if (settings.contains(pos + Position(1, -1))) it.first else it.second) + (if (settings.contains(pos + Position(-1, 0))) it.first else it.second) + (if (settings.contains(pos + Position(0, 0))) it.first else it.second) + (if (settings.contains(pos + Position(1, 0))) it.first else it.second) + (if (settings.contains(pos + Position(-1, 1))) it.first else it.second) + (if (settings.contains(pos + Position(0, 1))) it.first else it.second) + (if (settings.contains(pos + Position(1, 1))) it.first else it.second)).toInt(2)] } fun tick(invert: Boolean) = TrenchMap( invert, lookups, yRange().flatMap { y -> xRange().mapNotNull { x -> Position(x, y).let { if (lookup(it, invert) > 0) it else null } } }.toSet() ) override fun toString() = yRange().joinToString("\n") { y -> xRange().joinToString("") { x -> if (settings.contains(Position(x, y))) { if (inverted) "." else "#" } else { if (inverted) "#" else "." } } } } fun String.toTrenchMap() = this.split("\n\n", limit = 2).let { (lookups, settings) -> TrenchMap( false, lookups.map { if (it == '#') 1 else 0 }, settings.lines() .flatMapIndexed { y, row -> row.mapIndexedNotNull { x, ch -> if (ch == '#') Position(x, y) else null } } .toSet() ) } fun main() { val part1 = readText("/day20input.txt").toTrenchMap().tick(true).apply { println(this) }.tick(false) .apply { println("-----\n$this") } .tick(true) .apply { println("-----\n$this") } println(readText("/day20input.txt").toTrenchMap().tick(true).tick(false).settings.size) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
2,614
advent-of-kotlin-2021
MIT License
src/Day08.kt
pimtegelaar
572,939,409
false
{"Kotlin": 24985}
import kotlin.math.max fun main() { data class Tree( val size: Int, var visible: Boolean = false, var up: Int = 0, var down: Int = 0, var left: Int = 0, var right: Int = 0, ) { val scenicScore get() = up * down * left * right } fun part1(input: List<String>): Int { val forest = input.map { line -> line.map { Tree(it.digitToInt()) } } forest.forEach { line -> var highest = -1 line.forEach { tree -> if (tree.size > highest) tree.visible = true highest = max(tree.size, highest) } highest = -1 line.reversed().forEach { tree -> if (tree.size > highest) tree.visible = true highest = max(tree.size, highest) } } val length = input.first().length for (x in 0 until length) { var highest = -1 forest.forEach { line -> val tree = line[x] if (tree.size > highest) tree.visible = true highest = max(tree.size, highest) } highest = -1 forest.reversed().forEach { line -> val tree = line[x] if (tree.size > highest) tree.visible = true highest = max(tree.size, highest) } } return forest.sumOf { line -> line.count { it.visible } } } fun calculateScenicScore(x: Int, y: Int, tree: Tree, forest: List<List<Tree>>) { for (i in x - 1 downTo 0) { val other = forest[y][i] tree.left++ if (tree.size <= other.size) { break } } val length = forest.first().size for (i in x + 1 until length) { val other = forest[y][i] tree.right++ if (tree.size <= other.size) { break } } for (i in y - 1 downTo 0) { val other = forest[i][x] tree.up++ if (tree.size <= other.size) { break } } for (i in y + 1 until forest.size) { val other = forest[i][x] tree.down++ if (tree.size <= other.size) { break } } } fun part2(input: List<String>): Int { val forest = input.map { line -> line.map { Tree(it.digitToInt()) } } forest.forEachIndexed { y, line -> line.forEachIndexed { x, tree -> calculateScenicScore(x, y, tree, forest) } } return forest.maxOf { it.maxOf { tree -> tree.scenicScore } } } val testInput = readInput("Day08_test") val input = readInput("Day08") val part1 = part1(testInput) check(part1 == 21) { part1 } println(part1(input)) val part2 = part2(testInput) check(part2 == 8) { part2 } println(part2(input)) }
0
Kotlin
0
0
16ac3580cafa74140530667413900640b80dcf35
3,069
aoc-2022
Apache License 2.0
src/main/kotlin/adventofcode/year2020/Day11SeatingSystem.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2020 import adventofcode.Puzzle import adventofcode.PuzzleInput // Eight directions going up, down, left, right, or diagonal private val directions = (-1..1).flatMap { dx -> (-1..1).map { dy -> Pair(dx, dy) } }.filter { it != Pair(0, 0) } class Day11SeatingSystem(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val seatMap by lazy { input.lines().map { it.split("") } } override fun partOne() = seatMap.iterate(4, List<List<String>>::getImmediateNeighbors) override fun partTwo() = seatMap.iterate(5, List<List<String>>::getNearestSeatNeighbors) } private fun List<List<String>>.getNearestSeatNeighbor(self: Pair<Int, Int>, direction: Pair<Int, Int>): String? { var x = self.first var y = self.second while ((x + direction.first) in first().indices && (y + direction.second) in indices) { val cx = x + direction.first val cy = y + direction.second if (this[cy][cx] != ".") return this[cy][cx] x += direction.first y += direction.second } return null } private fun List<List<String>>.getImmediateNeighbors(self: Pair<Int, Int>) = directions.mapNotNull { dir -> getOrNull(self.second + dir.second)?.getOrNull(self.first + dir.first) } private fun List<List<String>>.next(tolerance: Int, neighborFunction: List<List<String>>.(Pair<Int, Int>) -> List<String>) = mapIndexed { y, row -> List(row.size) { x -> val occupiedNeighbors = neighborFunction(this, Pair(x, y)).count { it == "#" } when { (this[y][x] == "L" && occupiedNeighbors == 0) -> "#" (this[y][x] == "#" && occupiedNeighbors >= tolerance) -> "L" else -> this[y][x] } } } private fun List<List<String>>.iterate(tolerance: Int, neighborFunction: List<List<String>>.(Pair<Int, Int>) -> List<String>) = generateSequence(this) { it.next(tolerance, neighborFunction) } .zipWithNext() .first { it.first == it.second } .first .sumOf { it.count { it == "#" } } private fun List<List<String>>.getNearestSeatNeighbors(self: Pair<Int, Int>) = directions .mapNotNull { dir -> getNearestSeatNeighbor(self, dir) }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,239
AdventOfCode
MIT License
src/Day13.kt
tigerxy
575,114,927
false
{"Kotlin": 21255}
import TreeNode.ListNode fun main() { fun part1(input: List<String>): Int = input .parseFile() .map { Pair(it[0], it[1]) } .map { it.first < it.second } .mapIndexed { index, b -> b.toInt() * (index + 1) } .sum() fun part2(input: List<String>): Int { val markers = listOf(2, 6) .map { ListNode(listOf(ListNode(listOf(TreeNode.NumberNode(it))))) } val parsedAndSortedInput = input .parseFile() .flatten() .appendAll(markers) .sortedWith(TreeNode::compareTo) return markers .map { parsedAndSortedInput.indexOf(it) } .map { it + 1 } .multiply() } val day = "13" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") val testOutput1 = part1(testInput) println("part1_test=$testOutput1") assert(testOutput1 == 13) val testOutput2 = part2(testInput) println("part2_test=$testOutput2") assert(testOutput1 == 0) val input = readInput("Day$day") println("part1=${part1(input)}") println("part2=${part2(input)}") } private fun List<String>.parseFile(): List<List<TreeNode>> = windowed(size = 2, step = 3) .map { it .map(::parse) .map(Pair<TreeNode, String>::first) } private fun parse(line: String): Pair<TreeNode, String> { val list = mutableListOf<TreeNode>() var left = line while (left.isNotEmpty()) { left = when (left.first()) { ']' -> { return Pair(ListNode(list), left.drop(1)) } ',' -> { left.drop(1) } '[' -> { val res = parse(left.drop(1)) list.add(res.first) res.second } else -> { val res = parseNumber(left) list.add(res.first) res.second } } } return Pair(ListNode(list), "") } private fun <A, B> Pair<A, B>.mapFirstIf(condition: (A) -> Boolean, transform: (A) -> A): Pair<A, B> = if (condition(first)) copy(first = transform(first)) else this private fun <A, B> Pair<A, B>.mapSecondIf(condition: (B) -> Boolean, transform: (B) -> B): Pair<A, B> = if (condition(second)) copy(second = transform(second)) else this private fun parseNumber(line: String): Pair<TreeNode, String> = Pair( line.takeWhile { it.isDigit() }.toInt().toNumberNode(), line.dropWhile { it.isDigit() } ) private fun Int.toNumberNode() = TreeNode.NumberNode(this) private fun String.splitBefore(delimiter: Char): Pair<String, String> { val i = indexOf(delimiter) return Pair(substring(0, i), substring(i, lastIndex)) } private sealed interface TreeNode { operator fun compareTo(other: TreeNode): Int = when { (this is NumberNode) && (other is NumberNode) -> this.value.compareTo(other.value) this is ListNode && other is ListNode -> this.compareToListNode(other) else -> this.toListNode().compareTo(other.toListNode()) } fun toListNode(): ListNode data class NumberNode(val value: Int) : TreeNode { override fun toListNode() = ListNode(listOf(this)) } data class ListNode(val value: List<TreeNode>) : TreeNode { override fun toListNode(): ListNode = this fun compareToListNode(other: ListNode): Int = value .zip(other.value) { a, b -> a.compareTo(b) } .find { it != 0 } ?: value.size.compareTo(other.value.size) } }
0
Kotlin
0
1
d516a3b8516a37fbb261a551cffe44b939f81146
3,852
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/day4/Day4.kt
cyril265
433,772,262
false
{"Kotlin": 39445, "Java": 4273}
package day4 import read import readToList val input = readToList("day4_input.txt").first().split(',') val boardLines = read("day4_board.txt").split("\r\n\r\n") fun main() { println(play(input, true)) println(play(input, false)) } private fun play(input: List<String>, matchFirst: Boolean): Int { val boards = toBoards() input.forEach { number -> boards.forEach { board -> board.board.forEach { line -> line.forEach { cell -> if (number == cell.value) { cell.matched = true } } } if (matchFirst && board.matches() || boards.all { it.matches() }) { return@play board.sumUnmatched() * number.toInt() } } } throw RuntimeException("Invalid solution") } private fun toBoards(): List<Board> { val boards = boardLines .map { line -> line.split("\r\n") .map { it.split(' ').filter { it.isNotBlank() }.map(::Cell) } } .map(::Board) return boards } data class Cell(val value: String, var matched: Boolean = false) data class Board(val board: List<List<Cell>>) { fun matches(): Boolean { return board.any { line -> line.all { it.matched } } || transpose(board).any { line -> line.all { it.matched } } } fun sumUnmatched(): Int { return board.sumOf { x -> x.filter { !it.matched }.sumOf { it.value.toInt() } } } } private fun transpose(source: List<List<Cell>>) = (source.first().indices).map { i -> (source.indices).map { j -> source[j][i] } }
0
Kotlin
0
0
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
1,691
aoc2021
Apache License 2.0
src/main/day12/day12.kt
rolf-rosenbaum
572,864,107
false
{"Kotlin": 80772}
package day12 import Point import readInput typealias Grid = MutableMap<Point, Char> fun main() { val input = readInput("main/day12/Day12") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int = input.solveFor('S') fun part2(input: List<String>): Int = input.solveFor('a') fun List<String>.solveFor(start: Char): Int { val grid = parse() val startPoint = grid.filter { it.value == 'S' }.keys.first() val goal = grid.filterValues { it == 'E' }.keys.first() grid[goal] = 'z' return grid.filter { it.value == start }.mapNotNull { grid[startPoint] = 'a' distance(it.key, goal, grid) }.minOf { it } } private fun distance(start: Point, goal: Point, grid: Grid): Int? { // the metaphor is to "flood" the terrain with water, always going in all 4 directions if the neighbouring point is not too high // and keep track of the distance. // As soon as the goal is "wet", we have our result val lake = mutableMapOf(start to 0) var distance = 0 var currentSize = 0 do { currentSize = lake.size distance = grid.floodValley(lake, distance) } while (!lake.containsKey(goal) && lake.size > currentSize) if (lake.size <= currentSize) { // there is no valid path from start to goal return null } return distance } fun Grid.floodValley(lake: MutableMap<Point, Int>, distance: Int): Int { lake.filterValues { it == distance }.forEach { (point, _) -> point.neighbours().filter { this[it] != null && this[it]!! - this[point]!! <= 1 }.forEach { if (!lake.containsKey(it)) lake[it] = distance + 1 } } return distance + 1 } fun List<String>.parse(): Grid { val result = mutableMapOf<Point, Char>() forEachIndexed { y, line -> line.forEachIndexed { x, c -> result[Point(x, y)] = c } } return result }
0
Kotlin
0
2
59cd4265646e1a011d2a1b744c7b8b2afe482265
1,953
aoc-2022
Apache License 2.0
src/Day03.kt
iownthegame
573,926,504
false
{"Kotlin": 68002}
class Rucksack(private val input: String) { private val itemsInFirstCompartment: CharArray private val itemsInSecondCompartment: CharArray private val sharedItems: Set<Char> init { val halfInputLength = input.length / 2 itemsInFirstCompartment = input.substring(0, halfInputLength).toCharArray() itemsInSecondCompartment = input.substring(halfInputLength).toCharArray() sharedItems = itemsInFirstCompartment.toSet().intersect(itemsInSecondCompartment.toSet()) } fun prioritiesOfSharedItems(): Int { var priorities = 0 for (char in sharedItems) { priorities += if (char.isLowerCase()) { char.code - 97 + 1 } else { char.code - 65 + 26 + 1 } } return priorities } } class RucksackGroup(private val groupLines: List<String>) { private val badge: Char init { var items = setOf<Char>() for (line in groupLines) { val currentItems = line.toCharArray() items = if (items.isEmpty()) { currentItems.toSet() } else { items.intersect(currentItems.toSet()) } } badge = items.first() // Assume we only have one badge } fun priorityOfBadge(): Int { return if (badge.isLowerCase()) { badge.code - 97 + 1 } else { badge.code - 65 + 26 + 1 } } } fun main() { fun getRucksacks(input: List<String>): Array<Rucksack> { var rucksacks = arrayOf<Rucksack>() for (line: String in input) { val rucksack = Rucksack(line) rucksacks += rucksack } return rucksacks } fun getRucksackGroups(input: List<String>): Array<RucksackGroup> { var rucksackGroups = arrayOf<RucksackGroup>() val length = input.size var index = 0 while (index < length) { val lines = input.subList(index, index+3) val rucksackGroup = RucksackGroup(lines) rucksackGroups += rucksackGroup index += 3 } return rucksackGroups } fun part1(input: List<String>): Int { val rucksacks = getRucksacks(input) return rucksacks.sumOf { it.prioritiesOfSharedItems() } } fun part2(input: List<String>): Int { val rucksackGroups = getRucksackGroups(input) return rucksackGroups.sumOf { it.priorityOfBadge() } } // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day03_sample") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readTestInput("Day03") println("part 1 result: ${part1(input)}") println("part 2 result: ${part2(input)}") }
0
Kotlin
0
0
4e3d0d698669b598c639ca504d43cf8a62e30b5c
2,832
advent-of-code-2022
Apache License 2.0
src/main/kotlin/advent/week1/ShortestPath.kt
reitzig
159,310,794
false
null
package advent.week1 /** * Reads in a maze/labyrinth/map from stdin, and * prints it with the shortest path from S to X to stdout. */ fun main() { val maze = readMaze(generateSequence { readLine() }) val path = Dijkstra.shortestPath(maze, maze.start, maze.end) println(maze + path) } interface ShortestPathSolver { /** * Compute the shortest path from `source` to `target` in `maze`. */ fun shortestPath(maze: Labyrinth, source: Node = maze.start, target: Node = maze.end): List<Node> } /** * Parses a [Labyrinth] as specified by the * [problem statement](https://blog.kotlin-academy.com/the-advent-of-kotlin-2018-week-1-229e442a143). */ fun readMaze(bigString: String): Labyrinth = readMaze(bigString.splitToSequence("\n")) /** * Parses a [Labyrinth] as specified by the * [problem statement](https://blog.kotlin-academy.com/the-advent-of-kotlin-2018-week-1-229e442a143). */ fun readMaze(rows: Sequence<String>): Labyrinth { val grid = rows.map { row -> row.map { when (it) { 'S' -> NodeType.Start 'X' -> NodeType.End '.' -> NodeType.Regular 'B' -> NodeType.Wall else -> throw IllegalArgumentException("Symbol '$it' not allowed") } }.toTypedArray() }.toList().toTypedArray() // Validate input requirements, which [Labyrinth] et al. rely on. require(grid.isNotEmpty()) require(grid[0].isNotEmpty()) require(grid.all { it.size == grid[0].size }) require(grid.map { row -> row.count { it == NodeType.Start } }.sum() == 1) require(grid.map { row -> row.count { it == NodeType.End } }.sum() == 1) return Labyrinth(grid) }
0
Kotlin
0
0
38911626f62bce3c59abe893afa8f15dc29dcbda
1,738
advent-of-kotlin-2018
MIT License
src/aoc2017/kot/Day21.kt
Tandrial
47,354,790
false
null
package aoc2017.kot import java.io.File object Day21 { fun solve(start: String, input: List<String>, iter: Int): Int { val lookUp = parsePatterns(input) var current = start.split("/").map { it.toCharArray() }.toTypedArray() repeat(iter) { val chunkSize = if (current.size % 2 == 0) 2 else 3 val listOfBlocks = splitIntoBlocks(current, chunkSize) current = mergeBlocks(listOfBlocks.map { lookUp[it.contentDeepHashCode()]!! }) } return current.sumBy { it.count { it == '#' } } } private fun splitIntoBlocks(current: Array<CharArray>, chunkSize: Int): List<Array<CharArray>> { if (current.size == chunkSize) return listOf(current) val blockCount = (current.size * current.size) / (chunkSize * chunkSize) val blocks = Array(blockCount) { Array(chunkSize) { CharArray(chunkSize) { '.' } } } for (y in 0 until current.size) { for (x in 0 until current.size) { val bOff = x / blocks[0].size + (y / blocks[0].size) * Math.sqrt(blockCount.toDouble()).toInt() val xOff = x % blocks[0].size val yOff = y % blocks[0].size blocks[bOff][xOff][yOff] = current[x][y] } } return blocks.toList() } private fun mergeBlocks(blocks: List<Array<CharArray>>): Array<CharArray> { if (blocks.size == 1) return blocks[0] val size = Math.sqrt((blocks.size * blocks[0].size * blocks[0].size).toDouble()).toInt() val result = Array(size) { CharArray(size) { '.' } } for (y in 0 until result.size) { for (x in 0 until result.size) { val bOff = x / blocks[0].size + (y / blocks[0].size) * Math.sqrt(blocks.size.toDouble()).toInt() val xOff = x % blocks[0].size val yOff = y % blocks[0].size result[x][y] = blocks[bOff][xOff][yOff] } } return result } private fun parsePatterns(input: List<String>): Map<Int, Array<CharArray>> { val patterns = mutableMapOf<Int, Array<CharArray>>() input.forEach { val (lhs, rhs) = it.split(" => ").map { it.split("/") } val rhsArr = rhs.map { it.toCharArray() }.toTypedArray() val permutations = generatePermutations(lhs).map { it.contentDeepHashCode() to rhsArr } patterns.putAll(permutations) } return patterns } private fun generatePermutations(s: List<String>): List<Array<CharArray>> { val result = mutableSetOf<List<String>>() var next = s repeat(4) { result.add(next) result.add(next.reversed()) result.add(next.map { it.reversed() }) next = rot(next) } return result.map { it.map { it.toCharArray() }.toTypedArray() } } private fun rot(grid: List<String>): List<String> = flip2DArray(grid).reversed() private fun flip2DArray(arr: List<String>): List<String> = arr.mapIndexed { index, _ -> arr.map { it[index] }.joinToString(separator = "") } } fun main(args: Array<String>) { val input = File("./input/2017/Day21_input.txt").readLines() val start = ".#./..#/###" println("Part One = ${Day21.solve(start, input, 5)}") println("Part Two = ${Day21.solve(start, input, 18)}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
3,082
Advent_of_Code
MIT License
src/year2023/day03/Day03.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day03 import check import readInput fun main() { val testInput = readInput("2023", "Day03_test") check(part1(testInput), 4361) check(part2(testInput), 467835) val input = readInput("2023", "Day03") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val partNums = mutableListOf<Int>() for (y in input.indices) { val line = input[y] val nums = line.splitIntoNums() var startIndex = 0 partNums += nums.filter { val numIndex = line.indexOf(it.toString(), startIndex) val length = it.toString().length startIndex = numIndex + length val adjacentParts = input.getAdjacentParts(numIndex, y, length) adjacentParts.isNotEmpty() } } return partNums.sum() } private fun part2(input: List<String>): Int { val gearRatios = mutableListOf<Int>() for (y in input.indices) { val line = input[y] val gearIndices = line.getAllIndexOf('*') gearRatios += gearIndices.map { input.getSurroundingNumbers(it, y) } .filter { it.size == 2 } .map { (num1, num2) -> num1 * num2 } } return gearRatios.sum() } private fun String.splitIntoNums() = split("[^0-9]".toRegex()).mapNotNull { it.toIntOrNull() } private fun List<String>.getAdjacentParts(x: Int, y: Int, xSize: Int): List<Char> { val adjacent = mutableListOf<Char?>() for (yi in y - 1..y + 1) { for (xi in x - 1..(x + xSize)) { adjacent += getOrNull(y - 1)?.getOrNull(xi) adjacent += getOrNull(y)?.getOrNull(xi) adjacent += getOrNull(y + 1)?.getOrNull(xi) } } return adjacent.filterNotNull().filter { !it.isDigit() && it != '.' } } private fun String.getAllIndexOf(char: Char): List<Int> { val indices = mutableListOf<Int>() var startIndex = 0 while (true) { val index = indexOf(char, startIndex) if (index == -1) { return indices } indices += index startIndex = index + 1 } } private fun List<String>.getSurroundingNumbers(x: Int, y: Int): List<Int> { val nums = mutableListOf<Int>() for (yi in y - 1..y + 1) { val line = getOrNull(yi) ?: continue val numsOnLine = line.splitIntoNums() var startIndex = 0 for (num in numsOnLine) { val numIndex = line.indexOf(num.toString(), startIndex) startIndex = numIndex + num.toString().length val xCoverageByNum = (numIndex - 1..startIndex) if (x in xCoverageByNum) { nums += num } } } return nums }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,709
AdventOfCode
Apache License 2.0
src/Day14.kt
cypressious
572,916,585
false
{"Kotlin": 40281}
fun main() { fun parseInsertions(input: List<String>) = input .drop(2) .associate { it.split(" -> ").let { (from, to) -> from to to[0] } } fun part1(input: List<String>): Int { var template = input.first().toList() val insertions = parseInsertions(input) repeat(10) { val newTemplate = mutableListOf<Char>() for (i in 0 until template.lastIndex) { newTemplate.add(template[i]) val inserted = insertions.getValue("" + template[i] + template[i + 1]) newTemplate.add(inserted) } newTemplate.add(template.last()) template = newTemplate } val entries = template.groupingBy { it }.eachCount().values return entries.max() - entries.min() } fun part2(input: List<String>): Long { val line = input.first() var pairs = line.toList() .windowed(2, 1) .map { "" + it[0] + it[1] } .groupingBy { it } .eachCount() .mapValues { it.value.toLong() } val insertions = parseInsertions(input) repeat(40) { val newPairs = mutableMapOf<String, Long>() for ((pair, count) in pairs) { val char = insertions.getValue(pair) newPairs.merge("" + pair[0] + char, count, Long::plus) newPairs.merge("" + char + pair[1], count, Long::plus) } pairs = newPairs } val counts = mutableMapOf<Char, Long>() for ((pair, count) in pairs) { counts.merge(pair[0], count, Long::plus) } counts.merge(line.last(), 1, Long::plus) return counts.values.max() - counts.values.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 1588) check(part2(testInput) == 2188189693529) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
169fb9307a34b56c39578e3ee2cca038802bc046
2,073
AdventOfCode2021
Apache License 2.0
src/Day05.kt
hoppjan
433,705,171
false
{"Kotlin": 29015, "Shell": 338}
fun main() { fun part1(input: List<Line>): Int { var diagram = diagram(input.neededDiagramSize()) input.forEach { diagram = it.drawHorizontalOrVerticalLine(diagram) } return diagram.countDangerousAreas() } fun part2(input: List<Line>): Int { var diagram = diagram(input.neededDiagramSize()) input.forEach { cloudLine -> diagram = cloudLine.drawAnyLine(diagram) } return diagram.countDangerousAreas() } // test if implementation meets criteria from the description val testInput = VentCloudInputReader.read("Day05_test") // testing part 1 val testSolution1 = 5 val testOutput1 = part1(testInput) printTestResult(1, testOutput1, testSolution1) check(testOutput1 == testSolution1) // testing part 2 val testSolution2 = 12 val testOutput2 = part2(testInput) printTestResult(2, testOutput2, testSolution2) check(testOutput2 == testSolution2) // using the actual input for val input = VentCloudInputReader.read("Day05") printResult(1, part1(input)) printResult(2, part2(input)) } data class Point(val x: Int, val y: Int) data class Line(val from: Point, val to: Point) typealias Diagram = List<List<Int>> fun diagram(size: Int) = List(size) { List(size) { 0 } } fun List<Line>.neededDiagramSize() = maxOf { line -> listOf(line.from.x, line.from.y, line.to.x, line.to.y).maxOf { it } } + 1 // add 1 for size so that biggest index fits inside fun Line.isVertical() = from.x == to.x fun Line.isHorizontal() = from.y == to.y fun Line.drawAnyLine(diagram: Diagram) = if (isHorizontal() || isVertical()) drawHorizontalOrVerticalLine(diagram) else // this assumes that every Line is either horizontal, vertical, or diagonal drawDiagonalLine(diagram) /** * Draws given horizontal or vertical [Line] in the [givenDiagram]. */ fun Line.drawHorizontalOrVerticalLine(givenDiagram: Diagram): Diagram = givenDiagram.map { it.toMutableList() }.toMutableList().apply { when { isHorizontal() -> for (i in from.x upTo to.x) this[i][from.y]++ isVertical() -> for (i in from.y upTo to.y) this[from.x][i]++ } } /** * Draws given diagonal [Line] in the [givenDiagram]. */ fun Line.drawDiagonalLine(givenDiagram: Diagram): Diagram { val diagram = givenDiagram.map { it.toMutableList() }.toMutableList() val xDirection = from.x direction to.x val yDirection = from.y direction to.y val range = 0..(from.x upTo to.x).rangeCount() for (index in range) diagram[index.xDirection(from.x)][index.yDirection(from.y)]++ return diagram } infix fun Int.direction(other: Int): Int.(Int) -> Int = if (this > other) { a -> a - this } else { a -> a + this } fun IntRange.rangeCount() = last - first fun Diagram.countDangerousAreas() = sumOf { row -> row.filter { it >= 2 }.size }
0
Kotlin
0
0
04f10e8add373884083af2a6de91e9776f9f17b8
2,973
advent-of-code-2021
Apache License 2.0
src/Day04.kt
treegem
572,875,670
false
{"Kotlin": 38876}
import common.readInput fun main() { val day = "04" fun part1(input: List<String>) = input .map { it.toSectionAssignmentPair() } .map { it.isOneFullyContainedByOther() } .count { it } fun part2(input: List<String>) = input .map { it.toSectionAssignmentPair() } .map { it.doAssignmentsOverlap() } .count { it } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) } private fun String.toSectionAssignmentPair() = this .split(',') .map { it.toSectionAssignment() } .let { SectionAssignmentPair(it.first(), it.last()) } private fun String.toSectionAssignment() = this .split('-') .let { SectionAssignment( start = it.first().toInt(), end = it.last().toInt() ) } private class SectionAssignmentPair( val first: SectionAssignment, val second: SectionAssignment, ) { fun isOneFullyContainedByOther() = first.containsFully(second) || second.containsFully(first) fun doAssignmentsOverlap(): Boolean = first.overlapsWith(second) } private class SectionAssignment( val start: Int, val end: Int, ) { fun containsFully(other: SectionAssignment) = this.start <= other.start && this.end >= other.end fun overlapsWith(other: SectionAssignment) = this.start in other.start..other.end || this.end in other.start..other.end || other.start in this.start..this.end || other.end in this.start..this.end }
0
Kotlin
0
0
97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8
1,820
advent_of_code_2022
Apache License 2.0
src/Day02.kt
eo
574,058,285
false
{"Kotlin": 45178}
// https://adventofcode.com/2022/day/2 fun main() { fun opponentHandShape(symbol: String) = when (symbol) { "A" -> HandShape.ROCK "B" -> HandShape.PAPER "C" -> HandShape.SCISSORS else -> error("$symbol is invalid!") } fun part1(input: List<String>): Int { fun myHandShape(symbol: String) = when (symbol) { "X" -> HandShape.ROCK "Y" -> HandShape.PAPER "Z" -> HandShape.SCISSORS else -> error("$symbol is invalid!") } fun roundScore(symbol1: String, symbol2: String): Int { val opponentHandShape = opponentHandShape(symbol1) val myHandShape = myHandShape(symbol2) val roundResult = when (opponentHandShape) { myHandShape.winsAgainst -> RoundResult.WIN myHandShape.losesAgainst -> RoundResult.LOSS else -> RoundResult.DRAW } return myHandShape.score + roundResult.score } return input .map { it.split(" ") } .sumOf { (symbol1, symbol2) -> roundScore(symbol1, symbol2) } } fun part2(input: List<String>): Int { fun roundResult(symbol: String) = when (symbol) { "X" -> RoundResult.LOSS "Y" -> RoundResult.DRAW "Z" -> RoundResult.WIN else -> error("$symbol is invalid!") } fun roundScore(symbol1: String, symbol2: String): Int { val opponentHandShape = opponentHandShape(symbol1) val roundResult = roundResult(symbol2) val myHandShape = when (roundResult) { RoundResult.LOSS -> opponentHandShape.winsAgainst RoundResult.DRAW -> opponentHandShape else -> opponentHandShape.losesAgainst } return myHandShape.score + roundResult.score } return input .map { it.split(" ") } .sumOf { (symbol1, symbol2) -> roundScore(symbol1, symbol2) } } val input = readLines("Input02") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) } private enum class HandShape(val score: Int) { ROCK(1) { override val winsAgainst get() = SCISSORS override val losesAgainst get() = PAPER }, PAPER(2) { override val winsAgainst get() = ROCK override val losesAgainst get() = SCISSORS }, SCISSORS(3) { override val winsAgainst get() = PAPER override val losesAgainst get() = ROCK }; abstract val winsAgainst: HandShape abstract val losesAgainst: HandShape } private enum class RoundResult(val score: Int) { LOSS(0), DRAW(3), WIN(6); }
0
Kotlin
0
0
8661e4c380b45c19e6ecd590d657c9c396f72a05
2,729
aoc-2022-in-kotlin
Apache License 2.0
src/Day08.kt
pmellaaho
573,136,030
false
{"Kotlin": 22024}
fun Char.height(): Int = toString().toInt() fun String.tallestBefore(idx: Int): Int { return substring(0, idx).maxOf { it.height() } } fun String.tallestAfter(idx: Int): Int { return substring(idx + 1).maxOf { it.height() } } fun main() { val treeColums: MutableMap<Int, String> = mutableMapOf() fun part1(input: List<String>): Int { val visibleHorizontal = buildList { input.forEachIndexed { i, line -> line.forEachIndexed { x, tree -> treeColums[x] = buildString { treeColums[x]?.let { append(it) } append(tree) } when (i) { 0 -> add(Pair(x, (input.lastIndex))) input.lastIndex -> add(Pair(x, 0)) else -> { when (x) { // 1st and last of each row 0, line.lastIndex -> add(Pair(x, (input.lastIndex - i))) // check 2nd las last of each row line.lastIndex - 1 -> { if (tree.height() > line.last().height()) { add(Pair(x, (input.lastIndex - i))) } } // trees that are taller than trees before or after it in each row else -> { if (tree.height() > line.tallestBefore(x)) { add(Pair(x, (input.lastIndex - i))) } else if (tree.height() > line.tallestAfter(x)) { add(Pair(x, (input.lastIndex - i))) } } } } } } } } val visibleVertical = buildList { treeColums.values.forEachIndexed { j, column -> column.forEachIndexed { y, tree -> when (j) { 0, column.lastIndex -> { /* skip 1st and last column */ } // trees that are taller than trees before or after it in each column else -> { if (y == 0 || y == column.lastIndex) { /* skip 1st and last for middle columns */ } else if (tree.height() > column.tallestBefore(y)) { add(Pair(j, (column.lastIndex - y))) } else if (tree.height() > column.tallestAfter(y)) { add(Pair(j, (column.lastIndex - y))) } } } } } } val visibleTrees = (visibleHorizontal + visibleVertical).toSet() println("Visible trees count: ${visibleTrees.size} and coordinates: $visibleTrees") return visibleTrees.size } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day08_test") // val res = part1(testInput) // check(res == 21) val input = readInput("Day08") println(part1(input)) // You guessed 1353, too low // println(part2(input)) }
0
Kotlin
0
0
cd13824d9bbae3b9debee1a59d05a3ab66565727
3,501
AoC_22
Apache License 2.0
src/Day12.kt
fedochet
573,033,793
false
{"Kotlin": 77129}
fun main() { fun parseHeight(char: Char): Int { require(char in 'a'..'z') return char - 'a' } data class Pos(val row: Int, val column: Int) { fun moveLeft() = Pos(row, column - 1) fun moveRight() = Pos(row, column + 1) fun moveUp() = Pos(row + 1, column) fun moveDown() = Pos(row - 1, column) } operator fun <E> List<List<E>>.get(pos: Pos): E = this[pos.row][pos.column] data class ParseGraphResult( val graph: List<List<Int>>, val start: Pos, val finish: Pos ) fun parseGraph(input: List<String>): ParseGraphResult { var from: Pos? = null var to: Pos? = null val result = mutableListOf<MutableList<Int>>() for ((row, rowLine) in input.withIndex()) { val resultRow = mutableListOf<Int>() result.add(resultRow) for ((column, heightChar) in rowLine.withIndex()) { val height = when (heightChar) { 'S' -> { from = Pos(row, column) parseHeight('a') } 'E' -> { to = Pos(row, column) parseHeight('z') } else -> parseHeight(heightChar) } resultRow.add(height) } } requireNotNull(from) requireNotNull(to) return ParseGraphResult(result, from, to) } data class PosAndDistance(val pos: Pos, val distance: Int) fun exploreGraph( graph: List<List<Int>>, start: Pos, canGo: (from: Int, to: Int) -> Boolean ): Sequence<PosAndDistance> = sequence { val rows = graph.size val columns = graph.first().size val queue = ArrayDeque(listOf(PosAndDistance(start, 0))) val visited = mutableSetOf<Pos>() while (queue.isNotEmpty()) { val (current, distance) = queue.removeFirst() if (!visited.add(current)) { continue } yield(PosAndDistance(current, distance)) val currentHeight = graph[current] val nextPositions = sequenceOf(current.moveLeft(), current.moveRight(), current.moveUp(), current.moveDown()) .filter { it.row in 0 until rows && it.column in 0 until columns } .filter { canGo(currentHeight, graph[it]) } .filter { it !in visited } queue += nextPositions.map { PosAndDistance(it, distance + 1) } } } fun part1(input: List<String>): Int { val (graph, start, finish) = parseGraph(input) return exploreGraph(graph, start, canGo = { from, to -> to <= from + 1 }) .first { it.pos == finish } .distance } fun part2(input: List<String>): Int { val (graph, _, finish) = parseGraph(input) return exploreGraph(graph, start = finish, canGo = { from, to -> from <= to + 1 }) .filter { graph[it.pos] == 0 } .minBy { it.distance } .distance } // 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)) }
0
Kotlin
0
1
975362ac7b1f1522818fc87cf2505aedc087738d
3,457
aoc2022
Apache License 2.0
src/Day11.kt
iam-afk
572,941,009
false
{"Kotlin": 33272}
fun main() { class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, val divisor: Long, val ifTrue: Int, val ifFalse: Int ) { var inspected: Long = 0 } fun List<String>.parse() = this.chunked(7) .map { chunk -> val items = chunk[1].substring(" Starting items: ".length).split(", ").map { it.toLong() }.toMutableList() val op = chunk[2].substring(" Operation: new = old ".length).split(' ').let { args -> when (args[0]) { "+" -> if (args[1] != "old") { arg: Long -> arg + args[1].toLong() } else { arg: Long -> arg + arg } "*" -> if (args[1] != "old") { arg: Long -> arg * args[1].toLong() } else { arg: Long -> arg * arg } else -> error("unsupported operation: ${chunk[2]}") } } val divisor = chunk[3].substring(" Test: divisible by ".length).toLong() val ifTrue = chunk[4].substring(" If true: throw to monkey ".length).toInt() val ifFalse = chunk[5].substring(" If false: throw to monkey ".length).toInt() Monkey(items, op, divisor, ifTrue, ifFalse) } .toTypedArray() fun Array<Monkey>.simulate(times: Int, transform: Monkey.(Long) -> Long): Long { repeat(times) { for (monkey in this) { for (item in monkey.items) { val level = transform(monkey, item) if (level % monkey.divisor == 0L) { this[monkey.ifTrue].items.add(level) } else { this[monkey.ifFalse].items.add(level) } monkey.inspected += 1 } monkey.items.clear() } } this.sortByDescending { it.inspected } return this[0].inspected * this[1].inspected } fun part1(input: List<String>): Long = input.parse().simulate(20) { operation(it) / 3 } fun part2(input: List<String>): Long { val monkeys = input.parse() val mod = monkeys.fold(1L) { acc, monkey -> acc * monkey.divisor } return monkeys.simulate(10_000) { operation(it) % mod } } // 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)) }
0
Kotlin
0
0
b30c48f7941eedd4a820d8e1ee5f83598789667b
2,606
aockt
Apache License 2.0
kotlin/src/main/kotlin/year2023/Day04.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 import kotlin.math.pow fun main() { val input = readInput("Day04") Day04.part1(input).println() Day04.part2(input).println() } object Day04 { fun part1(input: List<String>): Int { return input.sumOf { line -> val (_, numbers) = line.split(":") val (winningNumbers, myNumbers) = numbers.split("|") val setWinningNumbers = winningNumbers .split(" ") .filter { it != "" && it != " " } .map { it.trim().toInt() } .toSet() val howManyMatches = myNumbers .split(" ") .filter { it != "" && it != " " } .map { it.trim().toInt() } .count { setWinningNumbers.contains(it) } if (howManyMatches == 0) { 0.0 } else { 2.0.pow(howManyMatches - 1) } }.toInt() } fun part2(input: List<String>): Long { val map = mutableMapOf<Int, Long>() for (i in 1..(input.size)) { map[i] = 1 } for (line in input) { val (card, numbers) = line.split(":") val (winningNumbers, myNumbers) = numbers.split("|") val cardNumber = card.split("Card ")[1].trim().toInt() val setWinningNumbers = winningNumbers .split(" ") .filter { it != "" && it != " " } .map { it.trim().toInt() } .toSet() val howManyMatches = myNumbers .split(" ") .filter { it != "" && it != " " } .map { it.trim().toInt() } .count { setWinningNumbers.contains(it) } val howManyTimes = map[cardNumber]!! for (i in 1..howManyMatches) { val cardId = cardNumber + i if (cardId < (input.size + 1)) map[cardId] = map[cardId]!! + howManyTimes } } return map.values.sum() } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
2,056
advent-of-code
MIT License
src/Day12.kt
andrewgadion
572,927,267
false
{"Kotlin": 16973}
import java.util.PriorityQueue data class MapPos(val point: Pair<Int, Int>, val distance: Int) fun main() { fun Char.isEnd(): Boolean = this == 'E' fun Char.canStep(d: Char): Boolean { if (this == 'S') return true if (d.isEnd()) return this == 'z' return d.code - this.code <= 1 } fun List<String>.neighbours(point: Pair<Int, Int>): List<Pair<Int, Int>> { val (row, col) = point return listOf(row to col - 1, row - 1 to col, row to col + 1, row + 1 to col) .filter { (itR, itC) -> this.getOrNull(itR)?.getOrNull(itC)?.let(this[row][col]::canStep) ?: false } } fun findPath(initial: Pair<Int, Int>, input: List<String>): Int { val visited = mutableSetOf(initial) val paths = PriorityQueue<MapPos> { o1, o2 -> o1.distance - o2.distance } paths.add(MapPos(initial, 0)) while (paths.isNotEmpty()) { val cur = paths.poll() if (input[cur.point.first][cur.point.second].isEnd()) return cur.distance input.neighbours(cur.point).filterNot(visited::contains).forEach { paths.add(MapPos(it, cur.distance + 1)) visited.add(it) } } return -1 } fun part1(input: List<String>): Int { val startRow = input.indexOfFirst { it.contains('S') } val startCol = input[startRow].indexOf('S') return findPath(startRow to startCol, input) } fun part2(input: List<String>): Int { return input.flatMapIndexed { col: Int, rowStr: String -> rowStr.mapIndexed { row: Int, c: Char -> if (c == 'a') findPath(col to row, input) else -1 }.filterNot { it == -1 } }.min() } val input = readInput("day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4d091e2da5d45a786aee4721624ddcae681664c9
1,881
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2022/Day12.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2022 import utils.InputUtils import utils.Coordinates class Maze(val data: List<String>) { val start = findCoordinate('S') val end = findCoordinate('E') private fun findCoordinate(c: Char): Coordinates = findCoordinates(c).first() fun findCoordinates(c: Char): Sequence<Coordinates> = sequence { data.forEachIndexed {rowNum, row -> row.forEachIndexed { colNum, ch -> if (ch == c) yield(Coordinates(colNum, rowNum)) } }} fun heightAt(coord: Coordinates): Int { val (x,y) = coord return when { coord == start -> 'a'.code coord == end -> 'z'.code y < 0 || y >= data.size -> -10 x < 0 || x >= data[y].length -> -10 else -> data[y][x].code } } } fun main() { val testInput = """Sabqponm abcryxxl accszExk acctuvwj abdefghi""".split("\n") fun calculateDistanceToEnd(maze: Maze): HashMap<Coordinates, Int> { val distances = HashMap<Coordinates, Int>() val queue = ArrayDeque<Coordinates>() distances[maze.end] = 0 queue.add(maze.end) while (!queue.isEmpty()) { val pos = queue.removeFirst() val height = maze.heightAt(pos) val distance = distances[pos]!! pos.adjacent().filter { it !in distances && maze.heightAt(it) >= height - 1 } .forEach { queue.addLast(it) distances[it] = distance + 1 } } return distances } fun routeToEnd( maze: Maze, coord: Coordinates, distances: HashMap<Coordinates, Int> ): Sequence<Coordinates> = sequence { var pos = coord while (pos != maze.end) { val height = maze.heightAt(pos) pos = pos.adjacent().filter { it in distances && maze.heightAt(it) <= height + 1 } .sortedBy { distances[it] }.first() yield(pos) } } fun part1(input: List<String>): Int { val maze = Maze(input) val distances = calculateDistanceToEnd(maze) val seq = routeToEnd(maze, maze.start, distances) return seq.count() } fun part2(input: List<String>): Int { val maze = Maze(input) val distances = calculateDistanceToEnd(maze) return maze.findCoordinates('a') .filter { it in distances } .minOf { routeToEnd(maze, it, distances).count() } } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 31) val puzzleInput = InputUtils.downloadAndGetLines(2022, 12).toList() println(part1(puzzleInput)) println(part2(puzzleInput)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
2,866
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2023/day15/day15.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day15 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val initSeq = parseInitializationSequence(inputFile.bufferedReader().readLines()) println("Hash of initialization sequence is: ${initSeq.sumOf { it.hash() }}") println("Boxes focusing power: ${BoxesLine().initialize(initSeq).contents.sumOf { it.focusingPower }}") } sealed interface InitOperation { val lensLabel: String val boxId: Int get() = hash(lensLabel) override fun toString(): String fun hash() = hash(this.toString()) } data class RemoveOperation(override val lensLabel: String) : InitOperation { override fun toString() = "$lensLabel-" } data class AddOperation(val lens: Lens) : InitOperation { override val lensLabel = lens.label override fun toString() = "${lens.label}=${lens.focalLength}" } data class Lens(val label: String, val focalLength: Int) data class BoxesLine(val contents: List<Box> = List(size = 256, init = { Box(it, emptyList()) })) { fun initialize(initSeq: List<InitOperation>): BoxesLine = initSeq.fold(this) { boxes, operation -> BoxesLine( contents = boxes.contents.map { box -> if (box.id == operation.boxId) { when (operation) { is RemoveOperation -> box.remove(operation.lensLabel) is AddOperation -> box.add(operation.lens) } } else { box } } ) } } data class Box(val id: Int, val contents: List<Lens>) { val focusingPower: Int = contents .mapIndexed { index, lens -> (id + 1) * (index + 1) * lens.focalLength } .sum() fun remove(lensLabel: String): Box = copy(contents = contents.filter { it.label != lensLabel }) fun add(newLens: Lens): Box = copy(contents = if (contents.any { it.label == newLens.label }) { contents.map { if (it.label == newLens.label) newLens else it } } else { contents + newLens }) } fun parseInitializationSequence(lines: Iterable<String>): List<InitOperation> = lines.first() .split(',') .mapNotNull { Regex("^([a-zA-Z]+)(=([0-9]+)|-)$").find(it) } .map { when (val symbol = it.groups[2]!!.value.first()) { '-' -> RemoveOperation( lensLabel = it.groups[1]!!.value, ) '=' -> AddOperation( lens = Lens( label = it.groups[1]!!.value, focalLength = it.groups[3]!!.value.toInt(), ), ) else -> throw IllegalArgumentException("Unknown operation character: $symbol") } } fun hash(string: String): Int = string.fold(0) { acc, c -> ((acc + c.code) * 17) % 256 }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
3,054
advent-of-code
MIT License
src/main/kotlin/dev/bogwalk/batch8/Problem86.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch8 import dev.bogwalk.util.maths.pythagoreanTriplet /** * Problem 86: Cuboid Route * * https://projecteuler.net/problem=86 * * Goal: Find the number of distinct cuboids (ignoring rotations) that can be formed (with integer * dimensions and shortest route with integer length) up to a maximum size of MxMxM. * * Constraints: A <= M && B <= M && C <= M * 1 <= M <= 4e5 * * This is based on the premise that a spider can sit on the bottom corner of a cuboid room of * size 6x5x3, with a fly perched on the opposite ceiling corner. By travelling in the shortest * straight line, the spider can reach the fly on a path of distance 10. * * Considering all cuboid rooms that do not exceed M = 100, the amount that have a shortest path * with integer dimensions is 2060. * * e.g.: M = 99 * count = 1975 */ class CuboidRoute { /** * The cuboid room can be visualised by flattening it to 2D, showing that the 3 shortest path * candidates are formed by the hypotenuses of either a 6x8 right-angled triangle or a 9x5 * right-angled triangle. Only the 6x8 triangle has an integer hypotenuse (10), which is a * Pythagorean triplet. * * Solution uses a similar approach to the previously determined solutions for finding * perimeters of right-angled triangles (Batch 3 - Problem 39, Batch 7 - Problem 75). * * The amount of distinct cuboids is checked and counted twice to account for different * combinations, e.g. Pythagorean triplet (6, 8, 10) produces different sets of cuboids * depending on whether the longest side is 6 or 8. * * Given that the triplet's a (= m^2 - n^2) must be <= [max], setting the outer loop limit to * reflect the lowest value of a (so as not to miss any combinations) works fine but produces * very slow speeds as M increases. When M = 1e4, it took 46.91s to iterate through the 3 loops, * whereas it took the quick draw solution 4.81s to generate all counts accurately up to 4e5. */ fun countDistinctCuboids(max: Int): Long { var cuboids = 0L var m = 2 while (m <= (max + 1) / 2) { nextN@for (n in 1 until m) { var d = 0 try { while (true) { val triplet = pythagoreanTriplet(m, n, ++d) if (triplet.first > max && triplet.second > max) break if (triplet.first <= max && triplet.first >= triplet.second / 2) { cuboids += countCuboids(triplet.first, triplet.second) } if (triplet.second <= max && triplet.second >= triplet.first / 2) { cuboids += countCuboids(triplet.second, triplet.first) } } } catch (e: IllegalArgumentException) { // primitive triplet must have m XOR n as even & m and n co-prime (gcd == 1) continue@nextN } } m++ } return cuboids } /** * Returns a count of distinct cuboid combinations based on the assumption that [a] is the * longest side and [b] is a summation of the 2 other sides. * * e.g. Pythagorean triplet (6, 8, 10) produces 2 sets of combinations: * {(6, 2, 6), (6, 3, 5), (6, 4, 4)} when a=6 and b=8 & * {(8, 1, 5), (8, 2, 4), (8, 3, 3)} when a=8 and b=6 */ private fun countCuboids(a: Int, b: Int): Long { return if (a >= b) b / 2L else a - (b - 1) / 2L } /** * Project Euler specific implementation that requires the least value of M such that the * count of distinct cuboid rooms first exceeds [count]. */ fun getLeastM(count: Int): Int { val cumulativeCount = cuboidCountsQuickDraw() return cumulativeCount.indexOfFirst { it > count } } /** * Stores the cumulative sum of all distinct cuboid counts for quick access. * * Note that brute force shows highest m = 1414 for M = 4e5, so max of 1e6 chosen to ensure * no combinations are missed. * * Note that the list of single counts is identical to sequence A143714. * @see <a href=">https://oeis.org/A143714">Sequence A143714</a> * * @return array of possible cuboid combinations for every index = M. */ fun cuboidCountsQuickDraw(): LongArray { val maxM = 1_000_000 val singleCounts = LongArray(maxM + 1) var m = 2 while (m * m / 2 <= maxM) { nextN@for (n in 1 until m) { var d = 0 try { while (true) { val triplet = pythagoreanTriplet(m, n, ++d) if (triplet.first > maxM && triplet.second > maxM) break if (triplet.first <= maxM && triplet.first >= triplet.second / 2) { singleCounts[triplet.first] += countCuboids(triplet.first, triplet.second) } if (triplet.second <= maxM && triplet.second >= triplet.first / 2) { singleCounts[triplet.second] += countCuboids(triplet.second, triplet.first) } } } catch (e: IllegalArgumentException) { // primitive triplet must have m XOR n as even & m and n co-prime (gcd == 1) continue@nextN } } m++ } // lowest possible M = 3 var cumulative = 0L val allCounts = LongArray(maxM + 1) { i -> if (i < 3) 0L else { cumulative += singleCounts[i] cumulative } } return allCounts } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
5,963
project-euler-kotlin
MIT License
src/main/kotlin/com/ikueb/advent18/Day24.kt
h-j-k
159,901,179
false
null
package com.ikueb.advent18 import com.ikueb.advent18.model.* object Day24 { private const val DEFINITION = "(\\d+) units each with (\\d+) hit points (\\(([^)]+)\\) )?with an attack that does (\\d+) ([^ ]+) damage at initiative (\\d+)" fun getWinningUnits(input: List<String>) = battle(input).active().sumBy { it.count } fun getWinningImmuneUnits(input: List<String>) = generateSequence(1) { it + 1 } .map { battle(input, it) } .first { it.haveImmuneSystemWon() } .active() .sumBy { it.count } private fun battle(input: List<String>, immunePowerUp: Int = 0): Armies { val armies = parse(input, immunePowerUp).getTokens() while (armies.areFightingFit()) { val targets = mutableMapOf<ArmyGroup, ArmyGroup>() armies.activeAndSorted().forEach { group -> armies.active() .filter { group.isTarget(it) } .filterNot { it in targets.values } .sortedWith(compareBy( { group.calculateDamage(it) }, { it.effectivePowerForSorting() }, { it.initiativeForSorting() })) .firstOrNull()?.let { targets[group] = it } } targets.entries .sortedBy { (key, _) -> key.initiativeForSorting() } .forEach { (attacker, target) -> attacker.attack(target) } if (targets.size == 1 && targets.entries.first().toPair() .let { !it.first.willBeEffectiveAgainst(it.second) }) { break } } return armies } private fun parse(input: List<String>, immunePowerUp: Int): InputMap<ArmyGroup> { val split = input.lastIndexMatching { it.isEmpty() } return listOf( parseArmy(input.subList(0, split), immunePowerUp), parseArmy(input.drop(split + 1), immunePowerUp) ) } private fun parseArmy(input: List<String>, immunePowerUp: Int): Army { val army = input[0].dropLast(1) val powerUp = if (army == "Immune System") immunePowerUp else 0 return Army(input.drop(1) .parseWith(DEFINITION) { (n, hp, _, powers, x, xType, i) -> parsePowers(powers).let { ArmyGroup(army, n.toInt(), hp.toInt(), it["immune"] ?: emptySet(), it["weak"] ?: emptySet(), x.toInt() + powerUp, xType, i.toInt()) } }.toSet(), "") } private fun parsePowers(powers: String) = "([^;]*)(; )?(.*)".parseFor(powers) { (x, _, y) -> setOf(x, y).filterNot { it.isEmpty() } .map { parsePower(it) } .toMap() } private fun parsePower(power: String) = "([^ ]+) to (.*)".parseFor(power) { (power, types) -> power to types.split(", ".toRegex()).toSet() } } private typealias Armies = InputTokens<ArmyGroup> private fun Armies.areFightingFit() = active().groupBy { it.army }.size != 1 private fun Armies.haveImmuneSystemWon() = active().none { it.army == "Infection" } private typealias Army = InputLine<ArmyGroup> private data class ArmyGroup( val army: String, var count: Int, val hit: Int, val immuneTo: Set<String>, val weakTo: Set<String>, val attack: Int, val attackType: String, private val initiative: Int ) : InputToken(Point(-initiative, -count * attack)) { override fun isActive() = count > 0 fun effectivePower() = count * attack fun effectivePowerForSorting() = -effectivePower() fun isTarget(other: ArmyGroup) = isActive() && other.isActive() && army != other.army && attackType !in other.immuneTo fun calculateDamage(other: ArmyGroup) = effectivePowerForSorting().toDouble() * when (attackType) { in other.immuneTo -> 0 in other.weakTo -> 2 else -> 1 } fun initiativeForSorting() = -initiative fun willBeEffectiveAgainst(other: ArmyGroup) = army != other.army && effectivePower() / other.hit > 0 fun attack(other: ArmyGroup) { if (isTarget(other)) other.attacked(effectivePower(), attackType) } private fun attacked(attack: Int, attackType: String) { if (attackType !in immuneTo) { val potentialUnitsDamaged = (attack.toDouble() / hit) * if (attackType in weakTo) 2 else 1 val damaged = minOf(count, potentialUnitsDamaged.toInt()) count -= damaged point = Point(initiativeForSorting(), effectivePowerForSorting()) } } }
0
Kotlin
0
0
f1d5c58777968e37e81e61a8ed972dc24b30ac76
4,968
advent18
Apache License 2.0
src/Day02.kt
maciekbartczak
573,160,363
false
{"Kotlin": 41932}
fun main() { fun part1(input: List<String>): Int { return input .map { getRoundInput(it) } .sumOf { calculateScore(it.first, it.second) } } fun part2(input: List<String>): Int { return input .map { getRoundInput(it) } .sumOf { calculateScore(it.first, getPlayerPick(it.first, it.second)) } } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun calculateScore(opponent: String, player: String): Int { var score = shapeScores[player]!! if (matchingShape[opponent] == player) { score += 3 } else if (shapeBeatenBy[opponent] == player) { score += 6 } return score } fun getRoundInput(line: String): Pair<String, String> { val picks = line.split(" ") return picks[0] to picks[1] } fun getPlayerPick(opponentShape: String, outcome: String): String { return when (outcome) { "X" -> shapeBeats[opponentShape]!! "Y" -> matchingShape[opponentShape]!! "Z" -> shapeBeatenBy[opponentShape]!! else -> "" } } val shapeScores = mapOf( "X" to 1, "Y" to 2, "Z" to 3 ) val shapeBeatenBy = mapOf( "A" to "Y", "B" to "Z", "C" to "X" ) val shapeBeats = mapOf( "A" to "Z", "B" to "X", "C" to "Y" ) val matchingShape = mapOf( "A" to "X", "B" to "Y", "C" to "Z" )
0
Kotlin
0
0
53c83d9eb49d126e91f3768140476a52ba4cd4f8
1,543
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc23/Day05.kt
tahlers
725,424,936
false
{"Kotlin": 65626}
package aoc23 import kotlin.math.max import kotlin.math.min fun LongRange.overlap(range: LongRange): List<LongRange?> { val before = if (range.first < first) { range.first..(min(range.last, first - 1)) } else null val after = if (range.last > last) { max(range.first, last + 1)..range.last } else null val between = if (range.last >= first && range.first < (last + 1)) { max(range.first, first)..min(range.last, last) } else null return listOf(before, between, after) } object Day05 { data class MappingRange(val destinationStart: Long, val sourceStart: Long, val length: Long) { private val currentRange = (sourceStart)..<(sourceStart + length) fun mapRange(range: LongRange): List<LongRange?> { val overlaps = currentRange.overlap(range) val newBetween = if (overlaps[1] != null) { val offset = destinationStart - sourceStart overlaps[1]!!.first + offset..(overlaps[1]!!.last + offset) } else null return listOf(overlaps[0], newBetween, overlaps[2]) } } data class GardenMap(val name: String, val mappingRanges: List<MappingRange> = emptyList()) { fun addMappingRange(mappingRange: MappingRange): GardenMap = GardenMap(name, mappingRanges + mappingRange) fun mapInput(input: Long): Long { val mappingToUse = mappingRanges.firstOrNull { input in it.sourceStart..<(it.sourceStart + it.length) } return if (mappingToUse != null) { val offset = mappingToUse.destinationStart - mappingToUse.sourceStart input + offset } else input } fun mapRange(range: LongRange): List<LongRange> { val initialUnfinishedAndFinished = listOf(range) to emptyList<LongRange>() val folded = mappingRanges.fold(initialUnfinishedAndFinished) { acc, mappingRange -> val mapped = acc.first.map { mappingRange.mapRange(it) } val newFinished = mapped.mapNotNull { it[1] } val newUnfinished = mapped.flatMap { listOfNotNull(it[0], it[2]) } newUnfinished to (acc.second + newFinished) } return folded.first + folded.second } } data class Almanac(val seeds: List<Long>, val gardenMaps: List<GardenMap>) fun calculateLowestLocationNumber(input: String): Long { val almanac = parseInputToAlmanac(input) val locations = almanac.gardenMaps.fold(almanac.seeds) { acc, gardenMap -> acc.map { gardenMap.mapInput(it) } } return locations.min() } fun calculateLowestSeedRangeLocationNumber(input: String): Long { val almanac = parseInputToAlmanac(input) val seedRanges = almanac.seeds.windowed(2, step = 2) { (it.first())..<(it.first() + it.last()) } val mappedRanges = seedRanges.flatMap { seedRange -> val result = almanac.gardenMaps.fold(listOf(seedRange)) { acc, gardenMap -> acc.flatMap { gardenMap.mapRange(it) } } result } return mappedRanges.minOf { it.first } } private fun parseInputToAlmanac(input: String): Almanac { val seedLine = input.trim().lineSequence().first().substringAfter(':').trim() val seeds = seedLine.split(' ').map { it.toLong() } val mapLines = input.trim().lines().drop(2) val init = emptyList<GardenMap>() val gardenMaps = mapLines.fold(init) { acc, line -> if (line.trim().isEmpty()) { acc } else if (line.contains(':')) { val newGardenMap = GardenMap(line.substringBefore(" map:")) acc + newGardenMap } else { val (dest, source, length) = line.trim().split(' ').map { it.toLong() } val mappingRange = MappingRange(dest, source, length) val updatedMap = acc.last().addMappingRange(mappingRange) acc.dropLast(1) + updatedMap } } return Almanac(seeds, gardenMaps) } }
0
Kotlin
0
0
0cd9676a7d1fec01858ede1ab0adf254d17380b0
4,200
advent-of-code-23
Apache License 2.0
aoc-2021/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentyone/Day08.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwentyone import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.permutations import fr.outadoc.aoc.scaffold.readDayInput class Day08 : Day<Int> { private companion object { const val a = 'a' const val b = 'b' const val c = 'c' const val d = 'd' const val e = 'e' const val f = 'f' const val g = 'g' val segments = (a..g).toList() val digits = arrayOf( setOf(a, b, c, e, f, g), // 0 setOf(c, f), // 1 setOf(a, c, d, e, g), // 2 setOf(a, c, d, f, g), // 3 setOf(b, c, d, f), // 4 setOf(a, b, d, f, g), // 5 setOf(a, b, d, e, f, g), // 6 setOf(a, c, f), // 7 setOf(a, b, c, d, e, f, g), // 8 setOf(a, b, c, d, f, g) // 9 ) } private data class Configuration( val signals: List<Set<Char>>, val output: List<Set<Char>> ) private val input = readDayInput() .lineSequence() .map { line -> val (signals, output) = line.split(" | ") Configuration( signals = signals .split(' ') .map { signal -> signal.toSet() }, output = output .split(' ') .map { signal -> signal.toSet() } ) } override fun step1() = input.sumOf { state -> state.output.count { signal -> digits.count { segments -> segments.size == signal.size } == 1 } } override fun step2(): Int { val possibleMappings: List<Map<Char, Char>> = segments .permutations .map { permut -> permut.mapIndexed { index, seg -> segments[index] to seg }.toMap() } return input.sumOf { config -> val digitSet = digits.toSet() val correctMapping = possibleMappings .filter { mapping -> // Check that the digits of unique segment length match config.signals.first { it.size == digits[1].size }.translate(mapping) == digits[1] && config.signals.first { it.size == digits[4].size }.translate(mapping) == digits[4] && config.signals.first { it.size == digits[7].size }.translate(mapping) == digits[7] && config.signals.first { it.size == digits[8].size }.translate(mapping) == digits[8] } .first { mapping -> // Check that all digits can be mapped val signals = config.signals.map { signal -> signal.translate(mapping) }.toSet() digitSet == signals } val decodedOutput = config.output.map { output -> val translated = output.translate(correctMapping) val digit = digits.indexOf(translated) digit } decodedOutput.joinToString("").toInt() } } private fun Set<Char>.translate(mapping: Map<Char, Char>): Set<Char> = map { seg -> mapping.getValue(seg) }.toSet() override val expectedStep1 = 375 override val expectedStep2 = 1_019_355 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
3,487
adventofcode
Apache License 2.0
src/main/kotlin/algorithm/other.kt
oQaris
402,822,990
false
{"Kotlin": 147623}
package algorithm import com.github.shiguruikai.combinatoricskt.combinations import graphs.Graph fun redo(g: Graph, lambda: (u: Int, v: Int, w: Int) -> Int): Int { var count = 0 g.getEdges().forEach { edge -> g.setWeightEdg( edge.copy(weight = lambda(edge.first, edge.second, edge.weight)) ) ++count } return count } fun isClustering(g: Graph): Boolean { return findComponents(g).withIndex() .groupBy { it.value }.all { (_, values) -> val vertexInCmp = values.map { it.index } vertexInCmp.combinations(2).all { g.isCom(it[0], it[1]) } } } fun isClusteringMaxSize(g: Graph, maxSizeCluster: Int): Boolean { return findComponents(g).withIndex() .groupBy { it.value }.all { (_, values) -> if (values.size > maxSizeCluster) return false val vertexInCmp = values.map { it.index } vertexInCmp.combinations(2).all { g.isCom(it[0], it[1]) } } } fun findComponents(g: Graph): IntArray { val components = IntArray(g.numVer) var newCmp = 0 g.getVertices().forEach { v -> if (components[v] == 0) dfs(g, v, ++newCmp, components) } return components } private fun dfs(g: Graph, v: Int, component: Int, components: IntArray) { components[v] = component g.com(v).forEach { u -> if (components[u] == 0) dfs(g, u, component, components) } } fun distance(g1: Graph, g2: Graph): Int { val e1 = g1.getEdges() val e2 = g2.getEdges() return e1.union(e2).minus(e1.intersect(e2.toSet())).size }
1
Kotlin
0
2
2424cf11cf382c86e4fb40500dd5fded24f1858f
1,684
GraphProcessor
Apache License 2.0
src/Day12.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
class Grid(val width: Int, val src: Int, val dst: Int, val nodes: List<Int>) { fun neighbors(at: Int): List<Int> { val list = mutableListOf<Int>() if ((at % width) > 0) { list.add(at - 1) } if ((at % width) < (width - 1)) { list.add(at + 1) } if (at >= width) { list.add(at - width) } if (at < (nodes.size - width)) { list.add(at + width) } return list.filter { nodes[it] <= nodes[at] + 1 } } fun print(path: List<Int>? = null) { println("Grid: $width x ${nodes.size / width}, src: $src, dst: $dst") nodes.chunked(width).forEachIndexed { y, row -> row.forEachIndexed { x, c -> val idx = x + y * width if (idx == (path?.first() ?: src)) { print("S") } else if (idx == (path?.last() ?: dst)) { print("E") } else if (path?.contains(idx) == true) { print("#") } else { print(".") } } print("\n") } } fun shortestPathFrom(start: Int = src): List<Int> { val visited = mutableSetOf<Int>() val distances = nodes.indices.associateWith { Int.MAX_VALUE }.toMutableMap() val previous: MutableMap<Int, Int?> = nodes.indices.associateWith { null }.toMutableMap() val queue = mutableSetOf(start) visited.add(start) distances[start] = 0 while (queue.isNotEmpty()) { val at = queue.minBy { distances[it]!! } queue.remove(at) if (at == dst) { break } neighbors(at).filter { !visited.contains(it) }.forEach { val d = distances[at]!! + 1 if (d < distances[it]!!) { distances[it] = d previous[it] = at } queue.add(it) } visited.add(at) } val path = mutableListOf<Int>() var at = dst as Int? while (at != null && at != start && previous[at] != null) { path.add(at) at = previous[at] } return path.reversed() } } fun main() { fun parseGrid(input: List<String>): Grid { var src: Int = -1 var dst: Int = -1 val nodes = input.flatMapIndexed { y, line -> line.toCharArray().mapIndexed { x, c -> val code = when (c) { 'S' -> 'a'.code 'E' -> 'z'.code else -> c.code } val idx = x + y * line.length if (c == 'S') src = idx else if (c == 'E') dst = idx code } } return Grid(input.first().length, src, dst, nodes) } fun part1(input: List<String>): Int { val grid = parseGrid(input) val path = grid.shortestPathFrom() grid.print(path) return path.size } fun part2(input: List<String>): Int { val grid = parseGrid(input) val starts = grid.nodes.indices.filter { grid.nodes[it] == 'a'.code } var path: List<Int>? = null starts.forEach { val candidate = grid.shortestPathFrom(it) if (path == null || candidate.size in 1 until path!!.size) { path = candidate } } grid.print(path) return path!!.size } // 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)) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
3,852
advent-of-code-2022
Apache License 2.0
src/main/kotlin/twentytwentytwo/Day15.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo import twentytwentytwo.Structures.Point2d import java.math.BigInteger fun main() { val input = {}.javaClass.getResource("input-15.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val testInput = {}.javaClass.getResource("input-15-1.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val day = Day15(input) val test = Day15(testInput) println(test.part1(10)) println(test.part2(20, 4000000)) println(day.part1(2000000)) println(day.part2(4000000, 4000000)) } class Day15(private val input: List<String>) { var sensorToBeacon = input.map { val parts = it.split(": closest beacon is at x=") val s = parts[0].split("Sensor at ")[1].split("=", ",") val b = parts[1].split("=", ",") (Point2d(s[1].toInt(), s[3].toInt())) to Point2d(b[0].toInt(), b[2].toInt()) } fun part1(row: Int): Int { val possibleBeacons = sensorToBeacon.mapNotNull { (s, b) -> val dist = s.distanceTo(b) s.manRanges(dist, row) }.flatten().toSet() // remove any existing sensor or beacon on the row val taken = sensorToBeacon.mapNotNull { (s, b) -> when { s.y == row -> s b.y == row -> b else -> { null } } }.toSet().count() return possibleBeacons.size - taken } fun part2(max: Int, score: Int): BigInteger { sensorToBeacon.map { (s, b) -> (0..max).map { row -> val dst = s.distanceTo(b) row to s.manRanges(dst, row) }.filter { it.second != null } }.flatten().groupBy({ it.first }, { it.second!! }).forEach { (row, ranges) -> val sorted = ranges.sortedBy { it.first } // tried flatten here a couple of times... never stopped rrrrrruningggg.. var outer = sorted.first().last sorted.map { r -> if (outer + 1 < r.first) return (outer + 1).toBigInteger() * score.toBigInteger() + row.toBigInteger() else outer = maxOf(outer, r.last) } } error("no solution") } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
2,233
aoc202xkotlin
The Unlicense
src/main/kotlin/day11/Day11.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day11 import java.io.File import java.util.LinkedList fun parseMap(rows: List<String>): Array<IntArray> = rows.map { row -> row.trim().map { it - '0' }.toIntArray() }.toTypedArray() private fun expandAdjacentWithDiagonals(row: Int, column: Int, map: Array<IntArray>): List<Pair<Int, Int>> = (-1..1).flatMap { r -> (-1..1).map { c -> (r + row) to (c + column) } } .filterNot { (r, c) -> r < 0 || c < 0 || r >= map.size || c >= map[0].size || (r == row && c == column) } fun simulateStep(octopusMap: Array<IntArray>): Int { val traverseIndices = octopusMap.flatMapIndexed { index, row -> row.indices.map { index to it } } val cellsToVisit = LinkedList(traverseIndices) val visited = mutableSetOf<Pair<Int, Int>>() var flashes = 0 while (cellsToVisit.isNotEmpty()) { val current = cellsToVisit.removeFirst() val (x, y) = current when (octopusMap[x][y]) { 9 -> { octopusMap[x][y] = 0 visited.add(current) flashes += 1 cellsToVisit.addAll(expandAdjacentWithDiagonals(x, y, octopusMap)) } 0 -> if (!visited.contains(current)) octopusMap[x][y] += 1 // Can only flash once in (1..8) -> octopusMap[x][y] += 1 // 0 is intentionally ignored } } return flashes } fun simulateSteps(steps: Int, octopusMap: Array<IntArray>): Int = (1..steps).fold(0) { acc, _ -> acc + simulateStep(octopusMap) } fun countStepsUntilAllOctopusesSynchronize(octopusMap: Array<IntArray>): Int { fun allFlashed(map: Array<IntArray>): Boolean = map.all { energies -> energies.all { it == 0 } } return generateSequence(1) { it + 1 }.first { simulateStep(octopusMap) allFlashed(octopusMap) }.or(0) } fun main() { File("./input/day11.txt").useLines { lines -> val input = lines.toList() println(simulateSteps(100, parseMap(input))) println(countStepsUntilAllOctopusesSynchronize(parseMap(input))) } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
1,908
advent-of-code-2021
MIT License
src/day13/Code.kt
ldickmanns
572,675,185
false
{"Kotlin": 48227}
package day13 import readInput fun main() { val input = readInput("day13/input") // val input = readInput("day13/input_test") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int { var index = 0 return input.filter { it.isNotEmpty() }.chunked(2) { val leftPacket = parsePacket(it.first()) val rightPacket = parsePacket(it.last()) ++index if (areCorrectlyOrdered(leftPacket, rightPacket)!!) index else 0 }.sum() } private fun parsePacket(packet: String): List<Any> { var currentList = ListWithParent(null) val contents = packet.removeSurrounding("[", suffix = "]") var priorDigit: Int? = null for (content in contents) when { content.isDigit() -> { val digit = content.digitToInt() priorDigit?.let { val newValue = it * 10 + digit currentList.items.removeLast() currentList.items.add(newValue) priorDigit = newValue } ?: run { priorDigit = digit } currentList.items.add(digit) } content == '[' -> { val newList = ListWithParent(currentList) currentList.items.add(newList.items) currentList = newList priorDigit = null } content == ']' -> { currentList = currentList.parent ?: error("No parent available") priorDigit = null } content == ',' -> { priorDigit = null continue } else -> error("Invalid input") } return currentList.items } private data class ListWithParent( val parent: ListWithParent?, val items: MutableList<Any> = mutableListOf(), ) private fun areCorrectlyOrdered(left: Any, right: Any): Boolean? = when { left is Int && right is Int -> when { left < right -> true left > right -> false left == right -> null else -> error("Invalid input") } left is Int && right is List<*> -> areCorrectlyOrdered(listOf(left), right) left is List<*> && right is Int -> areCorrectlyOrdered(left, listOf(right)) left is List<*> && right is List<*> -> when { left.isEmpty() and right.isEmpty() -> null left.isEmpty() and right.isNotEmpty() -> true left.isNotEmpty() and right.isEmpty() -> false left.isNotEmpty() and right.isNotEmpty() -> { val result = areCorrectlyOrdered(left.first()!!, right.first()!!) result ?: areCorrectlyOrdered(left.drop(1), right.drop(1)) } else -> error("Invalid input") } else -> error("Invalid input") } fun part2(input: List<String>): Int = input .filter { it.isNotEmpty() } .toMutableList() .apply { add("[[2]]") add("[[6]]") } .map { parsePacket(it) } .sortedWith { o1, o2 -> areCorrectlyOrdered(o1, o2)?.let { if (it) -1 else 1 } ?: 0 } .foldIndexed(1) { index: Int, acc: Int, currentPacket: List<Any> -> if (currentPacket == listOf(listOf(2)) || currentPacket == listOf(listOf(6))) acc * (index + 1) else acc }
0
Kotlin
0
0
2654ca36ee6e5442a4235868db8174a2b0ac2523
3,148
aoc-kotlin-2022
Apache License 2.0
src/Day08.kt
ricardorlg-yml
573,098,872
false
{"Kotlin": 38331}
import Day08Solver.Direction.* class Day08Solver(private val input: List<List<Int>>, private val size: Int = input.size) { private enum class Direction { LEFT, RIGHT, UP, DOWN } private fun generateNeighbours(direction: Direction, row: Int, col: Int): Sequence<Int> { val range = when (direction) { LEFT -> (col - 1 downTo 0) RIGHT -> (col + 1 until size) UP -> (row - 1 downTo 0) DOWN -> (row + 1 until size) } return sequence { for (i in range) { yield( when (direction) { LEFT, RIGHT -> input[row][i] UP, DOWN -> input[i][col] } ) } } } fun part1(): Int { var visibleTrees = size * size - ((size - 2) * (size - 2)) for (row in 1 until size - 1) { for (col in 1 until size - 1) { val treeHeight = input[row][col] val treesOnTheLeft = generateNeighbours(LEFT, row, col) val treesOnTheRight = generateNeighbours(RIGHT, row, col) val treesFromTop = generateNeighbours(UP, row, col) val tressFromBottom = generateNeighbours(DOWN, row, col) if (treesOnTheLeft.all { treeHeight > it } || treesOnTheRight.all { treeHeight > it } || treesFromTop.all { treeHeight > it } || tressFromBottom.all { treeHeight > it }) { visibleTrees++ continue } } } return visibleTrees } fun part2(): Int { var result = Int.MIN_VALUE for (row in 1 until size - 1) { for (col in 1 until size - 1) { val treeHeight = input[row][col] val treesOnTheLeft = generateNeighbours(LEFT, row, col) val treesOnTheRight = generateNeighbours(RIGHT, row, col) val treesFromTop = generateNeighbours(UP, row, col) val tressFromBottom = generateNeighbours(DOWN, row, col) val visibleLeftTrees = countVisibleTrees(treesOnTheLeft, treeHeight) val visibleRightTress = countVisibleTrees(treesOnTheRight, treeHeight) val visibleTopTrees = countVisibleTrees(treesFromTop, treeHeight) val visibleBottomTrees = countVisibleTrees(tressFromBottom, treeHeight) val scenicScore = visibleLeftTrees * visibleRightTress * visibleTopTrees * visibleBottomTrees if (scenicScore > result) { result = scenicScore } } } return result } private fun countVisibleTrees(trees: Sequence<Int>, current: Int): Int { var visibleTrees = 0 for (tree in trees) { if (tree >= current) { visibleTrees++ break } else { visibleTrees++ } } return visibleTrees } } fun main() { fun parseInput(input: List<String>): List<List<Int>> { return input.map { line -> line.map { it.digitToInt() }} } val testInput = parseInput(readInput("Day08_test")) val testSolver = Day08Solver(testInput) check(testSolver.part1() == 21) check(testSolver.part2() == 8) val input = readInput("Day08").run { parseInput(this) } val solver = Day08Solver(input) println("Part 1: ${solver.part1()}") println("Part 2: ${solver.part2()}") }
0
Kotlin
0
0
d7cd903485f41fe8c7023c015e4e606af9e10315
3,537
advent_code_2022
Apache License 2.0
kotlin/src/main/kotlin/year2023/Day24.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 fun main() { val input = readInput("Day24") Day24.part1(input, 200_000_000_000_000L, 400_000_000_000_000L).println() Day24.part2().println() } object Day24 { fun part1(input: List<String>, atLeast: Long, atMost: Long): Int { return input .getHailstones() .howManyIntersections(atLeast, atMost) } data class Location(val x: Long, val y: Long, val z: Long) data class Velocity(val dx: Long, val dy: Long, val dz: Long) private data class Hailstone( val location: Location, val velocity: Velocity ) { val slopeXY = velocity.dy / velocity.dx.toDouble() val a = -slopeXY private val c = -slopeXY * location.x + location.y fun intersectionXY(other: Hailstone): Pair<Double, Double>? { val determinant = this.a - other.a if (0.0 == determinant) { return null } return Pair( (this.c - other.c) / determinant, (this.a * other.c - other.a * this.c) / determinant ) } fun isFutureXY(xy: Pair<Double, Double>): Boolean { return ((xy.first - location.x) * velocity.dx) >= 0 && ((xy.second - location.y) * velocity.dy >= 0) } } private fun List<String>.getHailstones(): List<Hailstone> { return this.map { line -> line.split("@") } .map { line -> val location = line[0].split(",").map { it.trim().toLong() } val velocity = line[1].split(",").map { it.trim().toLong() } Hailstone( Location(location[0], location[1], location[2]), Velocity(velocity[0], velocity[1], velocity[2]) ) } } private fun List<Hailstone>.howManyIntersections(atLeast: Long, atMost: Long): Int { var count = 0 for (i in this.indices) { for (j in i + 1..<this.size) { val hailstone1 = this[i] val hailstone2 = this[j] if (hailstone1.slopeXY == hailstone2.slopeXY) { continue } val intersect = hailstone1.intersectionXY(hailstone2)!! if (hailstone1.isFutureXY(intersect) && hailstone2.isFutureXY(intersect) && atLeast <= intersect.first && intersect.first <= atMost && atLeast <= intersect.second && intersect.second <= atMost ) { count++ } } } return count } fun part2(): String { return "Resolved in Python using Z3 check resources/year2023/Day24_part2.py" } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
2,763
advent-of-code
MIT License
src/Day13.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
import com.github.h0tk3y.betterParse.combinators.* import com.github.h0tk3y.betterParse.grammar.Grammar import com.github.h0tk3y.betterParse.grammar.parseToEnd import com.github.h0tk3y.betterParse.grammar.parser import com.github.h0tk3y.betterParse.lexer.literalToken import com.github.h0tk3y.betterParse.lexer.regexToken import com.github.h0tk3y.betterParse.parser.Parser private sealed class Packet : Comparable<Packet> { data class Value(val value: Int) : Packet() { override fun compareTo(other: Packet): Int { return when (other) { is Packets -> Packets(listOf(this)).compareTo(other) is Value -> value.compareTo(other.value) } } } data class Packets(val packets: List<Packet>): Packet() { override fun compareTo(other: Packet): Int { return when (other) { is Packets -> packets.zip(other.packets) .firstNotNullOfOrNull { (left, right) -> left.compareTo(right).takeUnless { it == 0 } } ?: packets.size.compareTo(other.packets.size) is Value -> this.compareTo(Packets(listOf(other))) } } } } private val packetGrammar = object : Grammar<Packet.Packets>() { val number by regexToken("\\d+") val comma by literalToken(",") val leftBracket by literalToken("[") val rightBracket by literalToken("]") val value by number use { Packet.Value(text.toInt()) } val term by value or parser { packets } val packets: Parser<Packet.Packets> by -leftBracket * (separated(term, comma, acceptZero = true) use { Packet.Packets(terms) }) * -rightBracket override val rootParser by packets } fun main() { fun part1(input: String): Int { return input.splitToSequence("\n\n") .map { pair -> pair.lines().map { packetGrammar.parseToEnd(it) } } .withIndex() .sumOf { (index, pair) -> if (pair.sorted() == pair) index + 1 else 0 } } fun part2(input: String): Int { val dividerPackets = setOf("[[2]]", "[[6]]").map { packetGrammar.parseToEnd(it) }.toSet() val packets = input.lineSequence().filter { it.isNotBlank() }.map { packetGrammar.parseToEnd(it) } .plus(dividerPackets) .sorted() .toList() return dividerPackets.map { packets.indexOf(it) + 1 }.reduce(Int::times) } // test if implementation meets criteria from the description, like: val testInput = readText("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readText("Day13") with(part1(input)) { check(this == 5208) println(this) } with(part2(input)) { check(this == 25792) println(this) } }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
2,819
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-15.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import kotlin.math.absoluteValue import kotlin.math.max fun main() { val input = readInputLines(2022, "15-input") val testInput1 = readInputLines(2022, "15-test1") println("Part1:") part1(testInput1, 10).println() part1(input, 2000000).println() println() println("Part2:") part2(testInput1, 20).println() part2(input, 2000000).println() } private fun part1(input: List<String>, testY: Int): Int { val regex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex() val parsed = input.map { val (x1, y1, x2, y2) = regex.matchEntire(it)!!.destructured Coord2D(x1.toInt(), y1.toInt()) to Coord2D(x2.toInt(), y2.toInt()) } val full = fullInRow(parsed, testY) - parsed.map { it.second }.toSet().count { it.y == testY } return full } private fun part2(input: List<String>, size: Int): Long { val regex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex() val parsed = input.map { val (x1, y1, x2, y2) = regex.matchEntire(it)!!.destructured Coord2D(x1.toInt(), y1.toInt()) to Coord2D(x2.toInt(), y2.toInt()) } for (y in 0 until size) { val x = emptyInRow(parsed, y, 0 until size) if (x != null) { return x * 4000000L + y } } return 0 } private fun fullInRow(parsed: List<Pair<Coord2D, Coord2D>>, row: Int): Int { val ranges = parsed.mapNotNull { (sensor, beacon) -> val distToBeacon = sensor.distanceTo(beacon) val distToTestLine = (row - sensor.y).absoluteValue val distInRow = distToBeacon - distToTestLine (sensor.x - distInRow.. sensor.x + distInRow).takeIf { !it.isEmpty() } }.sortedBy { it.first } var count = 0 var x = ranges.first().first for (r in ranges) { if (x < r.first) { count += r.count() x = r.last + 1 } if (r.first <= x && x <= r.last) { count += r.last - x + 1 x = r.last + 1 } } return count } private fun emptyInRow(parsed: List<Pair<Coord2D, Coord2D>>, row: Int, range: IntRange): Int? { val ranges = parsed.mapNotNull { (sensor, beacon) -> val distToBeacon = sensor.distanceTo(beacon) val distToTestLine = (row - sensor.y).absoluteValue val distInRow = distToBeacon - distToTestLine (sensor.x - distInRow.. sensor.x + distInRow).takeIf { !it.isEmpty() } }.sortedBy { it.first } var x = range.first for (r in ranges) { when { x < r.first -> return x range.last < x -> return null else -> x = max(x, r.last + 1) } } return if (x < range.last) x else null } private const val testInput1 = """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""" private const val input = """Sensor at x=3523437, y=2746095: closest beacon is at x=3546605, y=2721324 Sensor at x=282831, y=991087: closest beacon is at x=743030, y=-87472 Sensor at x=1473740, y=3283213: closest beacon is at x=1846785, y=3045894 Sensor at x=1290563, y=46916: closest beacon is at x=743030, y=-87472 Sensor at x=3999451, y=15688: closest beacon is at x=3283637, y=-753607 Sensor at x=1139483, y=2716286: closest beacon is at x=1846785, y=3045894 Sensor at x=3137614, y=2929987: closest beacon is at x=3392051, y=3245262 Sensor at x=2667083, y=2286333: closest beacon is at x=2126582, y=2282363 Sensor at x=3699264, y=2920959: closest beacon is at x=3546605, y=2721324 Sensor at x=3280991, y=2338486: closest beacon is at x=3546605, y=2721324 Sensor at x=833202, y=92320: closest beacon is at x=743030, y=-87472 Sensor at x=3961416, y=2485266: closest beacon is at x=3546605, y=2721324 Sensor at x=3002132, y=3500345: closest beacon is at x=3392051, y=3245262 Sensor at x=2482128, y=2934657: closest beacon is at x=1846785, y=3045894 Sensor at x=111006, y=2376713: closest beacon is at x=354526, y=3163958 Sensor at x=424237, y=2718408: closest beacon is at x=354526, y=3163958 Sensor at x=3954504, y=3606495: closest beacon is at x=3392051, y=3245262 Sensor at x=2275050, y=2067292: closest beacon is at x=2333853, y=2000000 Sensor at x=1944813, y=2557878: closest beacon is at x=2126582, y=2282363 Sensor at x=2227536, y=2152792: closest beacon is at x=2126582, y=2282363 Sensor at x=3633714, y=1229193: closest beacon is at x=3546605, y=2721324 Sensor at x=1446898, y=1674290: closest beacon is at x=2333853, y=2000000 Sensor at x=3713985, y=2744503: closest beacon is at x=3546605, y=2721324 Sensor at x=2281504, y=3945638: closest beacon is at x=1846785, y=3045894 Sensor at x=822012, y=3898848: closest beacon is at x=354526, y=3163958 Sensor at x=89817, y=3512049: closest beacon is at x=354526, y=3163958 Sensor at x=2594265, y=638715: closest beacon is at x=2333853, y=2000000"""
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
5,745
advent-of-code
MIT License
src/Day11.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
import java.math.BigInteger fun main() { fun bothParts(input: String, rounds: Int, worried: Boolean): Long { val regex = """ (Monkey (\d): Starting items: ([\d,\s]*) Operation: new = old (\+|\*) (\w+) Test: divisible by (\d+) If true: throw to monkey (\d) If false: throw to monkey (\d)) """.trimIndent().toRegex() val monkeys = regex.findAll(input).mapIndexed { index, matchResult -> val items = matchResult.groups[3]?.value?.split(", ")?.map { it.toBigInteger() }?.toMutableList()!! val monkey = Monkey( index, items, { a: BigInteger -> interacts(a, matchResult.groups[5]?.value!!, matchResult.groups[4]?.value!!) }, matchResult.groups[6]?.value?.toInt()!!, matchResult.groups[7]?.value?.toInt()!!, matchResult.groups[8]?.value?.toInt()!!, 0 ) monkey }.toList() val modulo = monkeys .map { it.divideBy } .reduce { acc, i -> acc * i } for (round in 1..rounds) { monkeys.forEach { m -> m.items.forEach { item -> val number = m.op(item) m.interactions += 1 throws(worry(worried, number, modulo), m.divideBy, m.monkeyOne, m.monkeyTwo, monkeys) } m.items = mutableListOf() } } val topTwo = monkeys.map { m -> m.interactions }.sortedDescending().take(2) return topTwo[0] * topTwo[1].toLong() } fun part1(input: String, rounds: Int, worried: Boolean): Long { return bothParts(input, rounds, worried) } fun part2(input: String): Long { return bothParts(input, 10000, false) } val testInput = readText("Day11_test") check(part1(testInput, 20, true) == 10605.toLong()) check(part1(testInput, 10000, false) == 2713310158) val input = readText("Day11") println(part1(input, 20, true)) println(part2(input)) } data class Monkey(val id: Int, var items: MutableList<BigInteger>, val op: (BigInteger) -> BigInteger, val divideBy: Int, val monkeyOne: Int, val monkeyTwo: Int, var interactions: Int) fun interacts(old: BigInteger, number: String, sign: String): BigInteger { val n = if (number == "old") old else number.toBigInteger() return when (sign) { "*" -> old * n "+" -> old + n else -> throw IllegalArgumentException("how to handle $sign?") } } fun throws(worryLevel: BigInteger, divideBy: Int, monkeyOne: Int, monkeyTwo: Int, monkeys: List<Monkey>) { if (worryLevel.mod(divideBy.toBigInteger()) == 0.toBigInteger()) monkeys[monkeyOne].items.add(worryLevel) else monkeys[monkeyTwo].items.add(worryLevel) } fun worry(youShould: Boolean, number: BigInteger, modulo: Int): BigInteger { return if (youShould) number / 3.toBigInteger() else number.mod(modulo.toBigInteger()) }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
3,116
advent-of-code-kotlin-2022
Apache License 2.0
src/commonMain/kotlin/sequences/Distinct.kt
tomuvak
511,086,330
false
{"Kotlin": 92304, "Shell": 619}
package com.tomuvak.util.sequences /** * Returns a sequence which yields the exact same elements as the receiver sequence [this], in the same order, but * without repetitions – that is elements which have already appeared before are filtered out, and also stopping as soon * as [maxConsecutiveAttempts] (which has to be positive) consecutive elements have been filtered out this way, if ever. * * This is similar to the standard library's `distinct` extension function, but with the added functionality of the * returned sequence stopping when [maxConsecutiveAttempts] consecutive elements are repetitions of past elements. One * case where this is useful is when the receiver sequence [this] is potentially infinite but containing only a finite * number of _distinct_ elements: in that case the standard library's `.distinct()` will return a sequence which enters * an infinite loop (after retrieving all unique values, trying to retrieve the next value will not fail – it will * simply never return), whereas the sequence returned by this function will stop (note that this does **not** mean that * the returned sequence can never be infinite: it will be if the original sequence is itself infinite and _keeps * yielding **distinct** values_). Of course, this feature also means that it's possible for the returned sequence * _not_ to contain all distinct values contained in the original: any new value which follows more than * [maxConsecutiveAttempts] consecutive old values will be missed. * * This operation is _intermediate_ but _stateful_. */ fun <T> Sequence<T>.distinct(maxConsecutiveAttempts: Int): Sequence<T> = distinctBy(maxConsecutiveAttempts) { it } /** * Returns a sequence which yields the exact same elements as the receiver sequence [this], in the same order, but * without multiple elements having the same key as determined by the given [keySelector] – that is elements whose keys * have already appeared before are filtered out, and also stopping as soon as [maxConsecutiveAttempts] (which has to be * positive) consecutive elements have been filtered out this way, if ever. * * This is similar to the standard library's `distinctBy` extension function, but with the added functionality of the * returned sequence stopping when [maxConsecutiveAttempts] consecutive elements have keys which are repetitions of keys * of past elements. One case where this is useful is when the receiver sequence [this] is potentially infinite but * containing elements with only a finite number of _distinct_ keys: in that case the standard library's `.distinctBy()` * will return a sequence which enters an infinite loop (after retrieving elements with all unique keys, trying to * retrieve the next element will not fail – it will simply never return), whereas the sequence returned by this * function will stop (note that this does **not** mean that the returned sequence can never be infinite: it will be if * the original sequence is itself infinite and _keeps yielding elements with **distinct** keys_). Of course, this * feature also means that it's possible for the returned sequence _not_ to contain elements with all distinct keys of * elements from the original sequence: any element with a new key which follows more than [maxConsecutiveAttempts] * consecutive elements with old keys will be missed. * * This operation is _intermediate_ but _stateful_. */ fun <T, K> Sequence<T>.distinctBy(maxConsecutiveAttempts: Int, keySelector: (T) -> K): Sequence<T> { require(maxConsecutiveAttempts > 0) { "maxConsecutiveAttempts must be positive (was $maxConsecutiveAttempts)" } return DistinctSequence(this, maxConsecutiveAttempts, keySelector) } private class DistinctSequence<T, K>( private val source: Sequence<T>, private val maxConsecutiveAttempts: Int, private val keySelector: (T) -> K ): Sequence<T> { override fun iterator(): Iterator<T> = DistinctIterator(source.iterator(), maxConsecutiveAttempts, keySelector) } private class DistinctIterator<T, K>( private val source: Iterator<T>, private val maxConsecutiveAttempts: Int, private val keySelector: (T) -> K ): AbstractIterator<T>() { val pastValues = mutableSetOf<K>() var numAttempts = 0 override fun computeNext() { while (source.hasNext()) { val currentElement = source.next() if (pastValues.add(keySelector(currentElement))) { setNext(currentElement) numAttempts = 0 return } else if (++numAttempts >= maxConsecutiveAttempts) break } done() } }
0
Kotlin
0
0
e20cfae9535fd9968542b901c698fdae1a24abc1
4,630
util
MIT License
src/Day07.kt
ajmfulcher
573,611,837
false
{"Kotlin": 24722}
sealed class Node { var size = 0 } data class Directory( val name: String ): Node() { val nodes: MutableList<Node> = mutableListOf<Node>() var parent: Directory? = null } data class File( val name: String, ): Node() fun main() { fun Directory.findDirectory(name: String): Directory { return nodes.first { it is Directory && it.name == name } as Directory } fun Directory.directories() = nodes.mapNotNull { it as? Directory } fun Directory.totalSize() = nodes.map { it.size }.fold(0) { acc, i -> acc + i } fun create(input: List<String>): Directory { val root = Directory("/") val dummy = Directory("") dummy.nodes.add(root) root.parent = dummy var current = dummy input.forEach { line -> when { line == "$ cd .." -> current = current.parent ?: throw Error() line.startsWith("$ cd") -> current = current.findDirectory(line.split(" ")[2]) line.startsWith("dir") -> current.nodes.add( Directory(name = line.split(" ")[1]).apply { parent = current } ) line.matches(Regex("^\\d+.*")) -> { val e = line.split(" ") current.nodes.add( File(name = e[1]).apply { size = e[0].toInt() } ) } } } return root } fun computeSizes(dir: Directory, sizes: MutableList<Int>) { val directories = dir.directories() directories.forEach { d -> computeSizes(d, sizes) } dir.size = dir.totalSize() sizes.add(dir.size) } fun part1(input: List<String>): Int { val fs = create(input) val sizes = mutableListOf<Int>() computeSizes(fs, sizes) return sizes .filter{ it <= 100000 } .fold(0) { acc, i -> acc + i } } fun part2(input: List<String>): Int { val fs = create(input) val sizes = mutableListOf<Int>() computeSizes(fs, sizes) val unused = 70000000 - fs.size return sizes .filter { it >= 30000000 - unused } .sorted() .first() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") println(part1(testInput)) check(part1(testInput) == 95437) val input = readInput("Day07") println(part1(input)) println(part2(testInput)) check(part2(testInput) == 24933642) println(part2(input)) }
0
Kotlin
0
0
981f6014b09e347241e64ba85e0c2c96de78ef8a
2,590
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/aoc2021/Day12.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2021 import readInput private fun String.isLowerCase() = all { it.isLowerCase() } private class Graph(input: List<String>) { private val nodes: Collection<Node> private val start: Node private val end: Node init { val nodes = mutableMapOf<Node, Node>() input.forEach { line -> val newEdge = line.split("-").map { Node(it) }.map { node -> nodes.getOrPut(node) { node } } if (newEdge.size != 2) { throw IllegalArgumentException("aoc2021.Line $line is not valid") } newEdge[0].edges.add(newEdge[1]) newEdge[1].edges.add(newEdge[0]) } this.nodes = nodes.keys this.start = this.nodes.find { it.name == "start" } ?: throw IllegalArgumentException("No start node") this.end = this.nodes.find { it.name == "end" } ?: throw IllegalArgumentException("No end node") } data class Node(val name: String) { val edges = mutableSetOf<Node>() } /** * Finds all paths from [start] to [end] with the rules given by the part 1 description: No small cave can be * visited twice * @return all possible paths from [start] to [end] */ fun findPaths() = findPath(start, setOf(start), start) /** * Finds all paths from [start] to [end] with the rules given by the part 2 description: A single small cave can be * visited twice * @return all possible paths from [start] to [end] */ fun findPaths2() = findPath(start, setOf(start), null) /** * Finds the paths from [startNode] to [end] * @param startNode the node at which to start the search * @param alreadyVisited a set of already visited 'small' nodes * @param visitedTwice the small cave, that has been visited twice or null, if no small cave has been visited * twice so far * @return all possible paths from [startNode] to [end] */ private fun findPath(startNode: Node, alreadyVisited: Set<Node>, visitedTwice: Node?): Sequence<List<Node>> = sequence { for (node in startNode.edges) { when (node) { // start & end are never allowed to be visited twice -> always ending the current path start -> continue end -> yield(listOf(startNode, node)) else -> { val visitedNodes = alreadyVisited.toMutableSet() val remainingPaths = if (node.name.isLowerCase() && !visitedNodes.add(node)) { // is an already visited small cave if (visitedTwice != null) { emptySequence() } else { findPath(node, visitedNodes, node) } } else { // is a big cave, which can be visited regardless of the content of visitedNodes findPath(node, visitedNodes, visitedTwice) } remainingPaths.forEach { yield(buildList { add(startNode) addAll(it) }) } } } } } } private fun part1(input: List<String>) = Graph(input).findPaths().count() private fun part2(input: List<String>) = Graph(input).findPaths2().count() fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 226) check(part2(testInput) == 3509) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
3,885
adventOfCode
Apache License 2.0
src/Day12.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
import java.util.* private val dirs: List<Pair<Int, Int>> = listOf(0 to 1, 0 to -1, 1 to 0, -1 to 0) fun main() { fun bfs(graphHeights: List<List<Int>>, start: List<Pair<Int, Int>>, finish: Pair<Int, Int>): Int { val n = graphHeights.size val m = graphHeights[0].size val q: Queue<Pair<Int, Pair<Int, Int>>> = LinkedList() val used = MutableList(n) { MutableList(m) { false } } q.addAll(start.map { Pair(0, it) }) while (q.isNotEmpty()) { val (dist, xy) = q.remove() if (xy == finish) { return dist } if (used[xy]) continue used[xy] = true for (dir in dirs) { val nxy = xy + dir if (nxy.first !in 0 until n || nxy.second !in 0 until m || used[nxy] || graphHeights[nxy] > graphHeights[xy] + 1) continue q.add(Pair(dist + 1, nxy)) } } return -1 } fun findAllCharIn2D(input: List<String>, c: Char): List<Pair<Int, Int>> { val result: MutableList<Pair<Int, Int>> = mutableListOf() for (i in input.indices) { for (j in input[i].indices) { if (c == input[i][j]) { result.add(i to j) } } } return result } fun toHeightMap(input: List<String>) = input.map { it.map { it2 -> when (it2) { 'S' -> 0 'E' -> 'z' - 'a' else -> it2 - 'a' } } } fun part1(input: List<String>): Int { return bfs(toHeightMap(input), findAllCharIn2D(input, 'S'), findAllCharIn2D(input, 'E')[0]) } fun part2(input: List<String>): Int { return bfs( toHeightMap(input), findAllCharIn2D(input, 'a') + findAllCharIn2D(input, 'S'), findAllCharIn2D(input, 'E')[0] ) } // 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)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
2,215
advent-of-kotlin-2022
Apache License 2.0
src/y2023/d02/Day02.kt
AndreaHu3299
725,905,780
false
{"Kotlin": 31452}
package y2023.d02 import println import readInput fun main() { val classPath = "y2023/d02" fun possible(cubes: String): Boolean { return cubes .split(",") .map { it.trim().split(" ") } .all { when (it[1]) { "red" -> it[0].toInt() in 1..12 "green" -> it[0].toInt() in 1..13 "blue" -> it[0].toInt() in 1..14 else -> false } } } // The Elf would first like to know which games would have been possible if the bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes? fun part1(input: List<String>): Int { return input .map { Pair(it.split(":")[0].split(" ")[1], it.split(":")[1].split(";")) } .filter { draws -> draws.second.all { possible(it) } } .sumOf { it.first.toInt() } } fun getPower(sets: List<String>): Int { return sets .flatMap { it.split(",") } .map { Pair(it.trim().split(" ")[0], it.trim().split(" ")[1]) } .groupBy { it.second } .map { entry -> entry.value.maxOf { it.first.toInt() } } .reduce { acc, i -> acc * i } } fun part2(input: List<String>): Int { return input .map { it.split(":").let { x -> Pair( x[0].split(" ")[1], x[1].split(";") ) } } .sumOf { getPower(it.second) } } // test if implementation meets criteria from the description, like: val testInput = readInput("${classPath}/test") part1(testInput).println() part2(testInput).println() val input = readInput("${classPath}/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e
1,886
aoc
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2023/day02/day2.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day02 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val games = parseGames(inputFile.bufferedReader().readLines()) val possible = findPossibleGames(games, FULL_SET) println("Possible games are: ${possible.map { it.id }} with sum of IDs: ${sumGameIds(possible)}") println("Sum of powers of minimum sets: ${sumPowersOfMinimumSets(games)}") } val FULL_SET = CubeSet(red = 12, green = 13, blue = 14) data class Game(val id: Int, val sets: List<CubeSet>) { val minimumSet: CubeSet get() = CubeSet( red = sets.maxOf { it.red }, green = sets.maxOf { it.green }, blue = sets.maxOf { it.blue }, ) fun isPossible(fullSet: CubeSet) = sets.all { set -> set.isSubSetOf(fullSet) } } data class CubeSet(val red: Int = 0, val green: Int = 0, val blue: Int = 0) { val power: Int get() = red * green * blue fun add(count: Int, color: String): CubeSet { val (newRed, newGreen, newBlue) = when (color) { "red" -> Triple(count, 0, 0) "green" -> Triple(0, count, 0) "blue" -> Triple(0, 0, count) else -> throw IllegalArgumentException("Unknown color: $color") } return copy( red = red + newRed, green = green + newGreen, blue = blue + newBlue, ) } fun isSubSetOf(other: CubeSet) = this.red <= other.red && this.green <= other.green && this.blue <= other.blue } fun parseGames(lines: Iterable<String>): List<Game> = lines.map { line -> val parts = line.split(Regex("[:;]")) val id = parts[0].replace("Game ", "").toInt() val sets = parts.drop(1).map { setStr -> setStr.split(",").fold(CubeSet()) { acc, colorStr -> val (count, color) = colorStr.trim().split(" ") acc.add(count.toInt(), color) } } Game(id, sets) } fun findPossibleGames(games: List<Game>, fullSet: CubeSet): List<Game> = games.filter { it.isPossible(fullSet) } fun sumGameIds(games: List<Game>) = games.sumOf { it.id } fun sumPowersOfMinimumSets(games: List<Game>): Int = games.sumOf { it.minimumSet.power }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,332
advent-of-code
MIT License
src/Day07.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
import FSNode07.Dir import FSNode07.File fun main() { fun buildTree(input: List<String>): Dir { var current = Dir("/", null) for (line in input.drop(1)) { if (line.startsWith('$')) { if (line.startsWith("$ cd")) { val nextDir = line.split(' ')[2] current = if (nextDir == "..") current.parent!! else current .children .filter { it.name == nextDir } .filterIsInstance<Dir>() .firstOrNull() ?: Dir(nextDir, current) } } else if (line.startsWith("dir")) { current.children.add(Dir(line.split(' ')[1], current)) } else if (line.isBlank()) { // ignore } else { val (size, name) = line.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 toCheck = ArrayDeque<Dir>() toCheck.add(buildTree(input)) while (toCheck.isNotEmpty()) { val cur = toCheck.removeFirst() if (cur.size <= 100000) { smallDirs.add(cur) } toCheck.addAll(cur.children.filterIsInstance<Dir>()) } return smallDirs.sumOf { it.size } } fun part2(input: List<String>): Int { val root = buildTree(input) val needToFree = root.size - 40000000 val allDirs = sortedSetOf<Dir>({ o1, o2 -> o1.size.compareTo(o2.size) }) val toCheck = ArrayDeque<Dir>() toCheck.add(root) while (toCheck.isNotEmpty()) { val cur = toCheck.removeFirst() if (cur.size >= needToFree) allDirs.add(cur) toCheck.addAll(cur.children.filterIsInstance<Dir>()) } return allDirs .first() .size } val testInput = readInput("Day07_test") check(part1(testInput) == 95437) val input = readInput("Day07") println(part1(input)) println(part2(input)) } sealed interface FSNode07 { val size: Int val name: String val parent: Dir? data class File(override val name: String, override val size: Int, override val parent: Dir?) : FSNode07 data class Dir(override val name: String, override val parent: Dir?) : FSNode07 { val children = hashSetOf<FSNode07>() override val size: Int by lazy { children.sumOf { it.size } } } }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
2,700
aoc-2022
Apache License 2.0
src/Day03.kt
Nplu5
572,211,950
false
{"Kotlin": 15289}
fun main() { fun part1(input: List<String>): Int { return input.map { line -> Rucksack.fromLine(line) } .map { rucksack -> rucksack.getDoubleItem() } .sumOf { item -> item.mapToPriority() } } fun part2(input: List<String>): Int { return input.map { line -> Rucksack.fromLine(line) } .windowed(3, 3){ Group(it) } .map { group -> group.getBadge() } .sumOf { item -> item.mapToPriority() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") println(part2(testInput)) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } class Group(private val rucksacks: List<Rucksack>){ fun getBadge(): Item{ rucksacks.first().items.forEach {item -> if (item in rucksacks[1].items && item in rucksacks[2].items){ return item } } throw IllegalStateException("Group does not have a badge. Rucksacks: ${rucksacks.forEach { println(it) }}") } } data class Rucksack(val firstCompartment: List<Item>, val secondCompartment: List<Item>){ val items get() = firstCompartment.plus(secondCompartment) fun getDoubleItem(): Item { firstCompartment.forEach { item -> if (item in secondCompartment){ return item } } throw IllegalStateException("No doubled item in: $firstCompartment and $secondCompartment") } companion object { fun fromLine(line: String): Rucksack{ val firstCompartment = line.subSequence(0, line.length / 2 ).map { Item(it) } val secondCompartment = line.subSequence(line.length / 2, line.length).map { Item(it) } return Rucksack(firstCompartment, secondCompartment) } } } @JvmInline value class Item(val identifier: Char) private const val SMALL_CHAR_OFFSET = 96 private const val BIG_CHAR_OFFSET = 38 private val priorityDictionary = ('A'..'Z').map { it to it.code - BIG_CHAR_OFFSET} .plus(('a'..'z').map { it to it.code - SMALL_CHAR_OFFSET }) .toMap() fun Item.mapToPriority(): Int { return priorityDictionary[identifier] ?: throw IllegalArgumentException("Identifier $identifier not supported") }
0
Kotlin
0
0
a9d228029f31ca281bd7e4c7eab03e20b49b3b1c
2,360
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day5Solution.kt
yigitozgumus
434,108,608
false
{"Kotlin": 17835}
package days import BaseSolution import kotlin.math.abs data class Point(val x: Int, val y: Int) fun createPoint(locationList: List<Int>) = Point(locationList[0], locationList[1]) data class Line(val start: Point, val end: Point) { fun isHorizontalOrVertical(): Boolean = start.x == end.x || start.y == end.y fun isDiagonal(): Boolean = abs(start.x - end.x) == abs(start.y - end.y) fun generatePointMap(): List<Point> = when { start.x == end.x && start.y < end.y -> getRange(start.y, end.y).map { Point(start.x, it) } start.x == end.x -> getRange(start.y, end.y).map { Point(start.x, it) } start.y == end.y && start.x < end.x -> getRange(start.x, end.x).map { Point(it, start.y) } start.y == end.y -> getRange(start.x, end.x).map { Point(it, start.y) } else -> getRange(start.x, end.x).zip(getRange(start.y, end.y)).map { Point(it.first, it.second) } } } fun createLine(pointList: List<Point>) = Line(pointList[0], pointList[1]) fun getRange(start: Int, end: Int) = if (start < end) (start..end) else (start downTo end) class Day5Solution(inputList: List<String>) : BaseSolution(inputList) { private val lineList = inputList.map { pointPair -> pointPair.split(" -> ").map { point -> createPoint(point.split(",").map { it.toInt() }) } }.map { createLine(it) }.asSequence() override fun part1() { lineList.filter { it.isHorizontalOrVertical() } .flatMap { line -> line.generatePointMap() } .groupingBy { it } .eachCount().values.filter { it > 1 }.size .also { println(it) } } override fun part2() { lineList.filter { it.isDiagonal() || it.isHorizontalOrVertical() } .flatMap { line -> line.generatePointMap() } .groupingBy { it } .eachCount().values.filter { it > 1 }.size .also { println(it) } } }
0
Kotlin
0
0
c0f6fc83fd4dac8f24dbd0d581563daf88fe166a
1,928
AdventOfCode2021
MIT License
src/main/kotlin/io/github/aarjavp/aoc/day15/Day15.kt
AarjavP
433,672,017
false
{"Kotlin": 73104}
package io.github.aarjavp.aoc.day15 import io.github.aarjavp.aoc.readFromClasspath import java.util.* class Day15 { enum class Direction(val rowOffset: Int, val colOffset: Int) { UP(-1, 0), DOWN(1, 0), LEFT(0, -1), RIGHT(0, 1); companion object { val values = values().toList() } } data class Location(val row: Int, val col: Int) { operator fun plus(direction: Direction): Location = copy( row = row + direction.rowOffset, col = col + direction.colOffset ) } open class Grid(val riskLevels: ArrayList<String>, val rows: Int, val cols: Int) { private val rowRange = 0 until rows private val colRange = 0 until cols open operator fun get(location: Location): Int = riskLevels[location.row][location.col].digitToInt() operator fun contains(location: Location): Boolean = location.row in rowRange && location.col in colRange fun toPart2(): Grid2 = Grid2(riskLevels = riskLevels, templateRows = rows, templateCols = cols) } data class Path(val locations: ArrayList<Location>, val risk: Int) { val destination: Location get() = locations.last() } fun parseGrid(lines: Sequence<String>): Grid { val mapped = lines.toCollection(arrayListOf()) return Grid(mapped, rows = mapped.size, cols = mapped.first().length) } fun findPath(grid: Grid): Path { val visited = mutableSetOf<Location>() val pathsToWalk = PriorityQueue<Path>( Comparator.comparingInt { it.risk } ) pathsToWalk.add(Path(locations = arrayListOf(Location(0, 0)), risk = 0)) operator fun Path.plus(direction: Direction): Path? { val newDestination = destination + direction if (newDestination !in grid) return null val newLocations = ArrayList<Location>(locations.size + 1).apply { addAll(locations) } newLocations.add(newDestination) val newRisk = risk + grid[newDestination] return Path(locations = newLocations, risk = newRisk) } val destination = Location(grid.rows - 1, grid.cols - 1) while (pathsToWalk.isNotEmpty()) { val pathToExtend = pathsToWalk.poll() if (pathToExtend.destination == destination) { return pathToExtend } if (pathToExtend.destination !in visited) { visited += pathToExtend.destination for (direction in Direction.values) { val newPath = pathToExtend + direction newPath?.let { pathsToWalk.add(it) } } } } error("No path to $destination found. Visited $visited") } class Grid2(riskLevels: ArrayList<String>, val templateRows: Int, val templateCols: Int): Grid(riskLevels, templateRows * 5, templateCols * 5) { override operator fun get(location: Location): Int { val init = riskLevels[location.row % templateRows][location.col % templateCols].digitToInt() val additional = location.row / templateRows + location.col / templateCols val sum = init + additional return if (sum > 9) sum - 9 else sum } } } fun main() { val solution = Day15() val grid = readFromClasspath("Day15.txt").useLines { lines -> solution.parseGrid(lines) } val part1 = solution.findPath(grid).risk println(part1) val part2 = solution.findPath(grid.toPart2()).risk println(part2) }
0
Kotlin
0
0
3f5908fa4991f9b21bb7e3428a359b218fad2a35
3,564
advent-of-code-2021
MIT License
kotlin/src/com/s13g/aoc/aoc2020/Day5.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver import kotlin.math.pow /** * --- Day 5: Binary Boarding --- * https://adventofcode.com/2020/day/5 */ class Day5 : Solver { override fun solve(lines: List<String>): Result { return solveFast(lines) // Note, if I would have been clever I would have realized that this is just a binary encoding. // In any case, I am leaving this solution up as I want to show what I did to solve the problem int he moment. // val seats = lines.map { calcSeat(it) }.map { it.first * 8 + it.second }.toSet() // return Result("${seats.max()}", "${findSeat(seats)}") } // Solution for Part B private fun findSeat(occupiedSeats: Set<Int>): Int { for (x in 1..(127 * 8)) if (occupiedSeats.contains(x - 1) && !occupiedSeats.contains(x)) return x error("Cannot find free seat.") } } private fun calcSeat(line: String): Pair<Int, Int> { val r = Range(0, 127) val c = Range(0, 7) return Pair((0..6).map { line[it] }.map { r.process(it) }.last(), (7..9).map { line[it] }.map { c.process(it) }.last()) } private data class Range(var from: Int, var to: Int) private fun Range.process(c: Char): Int { if (c == 'F' || c == 'L') to = ((to - from) / 2) + from if (c == 'B' || c == 'R') from += ((to - from) / 2) return to } // Did this after I finally realized this is just binary encoding. private fun solveFast(lines: List<String>): Result { val occ = mutableSetOf<Int>() for (line in lines) { var v = line.withIndex().sumBy { if (it.value == 'B') 2.0.pow(6 - it.index).toInt() * 8 else 0 } v += line.withIndex().sumBy { if (it.value == 'R') 2.0.pow(9 - it.index).toInt() else 0 } occ.add(v) } val b = (0..(127 * 8)).minBy { if (it !in occ && it - 1 in occ) it else Int.MAX_VALUE } return Result("${occ.max()}", "$b") }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,864
euler
Apache License 2.0
src/Day11.kt
pavlo-dh
572,882,309
false
{"Kotlin": 39999}
fun main() { class Monkey( val items: ArrayDeque<Long>, val operation: Long.(Long) -> Long, val operand: Long?, val testConstant: Long, val testPassesMonkeyNumber: Int, val testFailsMonkeyNumber: Int, var itemsInspected: Long = 0L ) fun parseInput(input: List<String>): Map<Int, Monkey> = input.chunked(7).associate { monkeyInput -> val number = monkeyInput[0][7].digitToInt() val items = ArrayDeque(monkeyInput[1].substringAfter("items: ").split(", ").map(String::toLong)) val (operator, operandString) = monkeyInput[2].substringAfter("old ").split(' ') val operation: Long.(Long) -> Long = if (operator == "*") Long::times else Long::plus val operand = if (operandString != "old") operandString.toLong() else null val testConstant = monkeyInput[3].substringAfter("by ").toLong() val testPassesMonkeyNumber = monkeyInput[4].substringAfter("monkey ").toInt() val testFailsMonkeyNumber = monkeyInput[5].substringAfter("monkey ").toInt() number to Monkey(items, operation, operand, testConstant, testPassesMonkeyNumber, testFailsMonkeyNumber) } fun Monkey.performOperation(old: Long): Long { val operand = operand ?: old return old.operation(operand) } fun calculateMonkeyBusinessLevel( monkeys: Map<Int, Monkey>, repetitions: Int, reduceWorryLevel: (worryLevel: Long) -> Long ): Long { repeat(repetitions) { monkeys.forEach { (_, monkey) -> repeat(monkey.items.size) { val item = monkey.items.removeFirst() monkey.itemsInspected++ var worryLevel = monkey.performOperation(item) worryLevel = reduceWorryLevel(worryLevel) val nextMonkeyNumber = if (worryLevel % monkey.testConstant == 0L) { monkey.testPassesMonkeyNumber } else { monkey.testFailsMonkeyNumber } monkeys.getValue(nextMonkeyNumber).items.addLast(worryLevel) } } } return monkeys.values.sortedByDescending(Monkey::itemsInspected).take(2).let { it.first().itemsInspected * it.last().itemsInspected } } fun part1(input: List<String>): Long { val monkeys = parseInput(input) return calculateMonkeyBusinessLevel(monkeys, 20) { worryLevel -> worryLevel / 3 } } fun gcd(a: Long, b: Long): Long = if (a == 0L) b else gcd(b % a, a) fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b fun List<Long>.lcm(): Long = fold(first()) { result, element -> lcm(result, element) } fun part2(input: List<String>): Long { val monkeys = parseInput(input) val testConstantsLCM = monkeys.values.map(Monkey::testConstant).lcm() return calculateMonkeyBusinessLevel(monkeys, 10000) { worryLevel -> worryLevel % testConstantsLCM } } // 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)) }
0
Kotlin
0
2
c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992
3,379
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/DivideArrayIntoArraysWithMaxDifference.kt
Codextor
453,514,033
false
{"Kotlin": 26975}
/** * You are given an integer array nums of size n and a positive integer k. * * Divide the array into one or more arrays of size 3 satisfying the following conditions: * * Each element of nums should be in exactly one array. * The difference between any two elements in one array is less than or equal to k. * Return a 2D array containing all the arrays. If it is impossible to satisfy the conditions, return an empty array. * And if there are multiple answers, return any of them. * * * * Example 1: * * Input: nums = [1,3,4,8,7,9,3,5,1], k = 2 * Output: [[1,1,3],[3,4,5],[7,8,9]] * Explanation: We can divide the array into the following arrays: [1,1,3], [3,4,5] and [7,8,9]. * The difference between any two elements in each array is less than or equal to 2. * Note that the order of elements is not important. * Example 2: * * Input: nums = [1,3,3,2,7,3], k = 3 * Output: [] * Explanation: It is not possible to divide the array satisfying all the conditions. * * * Constraints: * * n == nums.length * 1 <= n <= 10^5 * n is a multiple of 3. * 1 <= nums[i] <= 10^5 * 1 <= k <= 10^5 * @see <a href="https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/">LeetCode</a> */ fun divideArray(nums: IntArray, k: Int): Array<IntArray> { val numsSize = nums.size val dividedArraysColumns = 3 val dividedArraysRows = numsSize / dividedArraysColumns val sortedNums = nums.sorted() val dividedArrays = Array<IntArray>(dividedArraysRows) { IntArray(dividedArraysColumns) } for (index in 0 until numsSize) { val row = index / dividedArraysColumns val column = index.rem(dividedArraysColumns) if (column == 0) { dividedArrays[row][column] = sortedNums[index] } else if (column == 1 && sortedNums[index] - sortedNums[index - 1] <= k) { dividedArrays[row][column] = sortedNums[index] } else if (column == 2 && sortedNums[index] - sortedNums[index - 2] <= k) { dividedArrays[row][column] = sortedNums[index] } else { return arrayOf<IntArray>() } } return dividedArrays }
0
Kotlin
1
0
68b75a7ef8338c805824dfc24d666ac204c5931f
2,149
kotlin-codes
Apache License 2.0
src/Day05.kt
cgeesink
573,018,348
false
{"Kotlin": 10745}
data class Command(val count: Int, val from: Int, val to: Int) { companion object { fun of(line: String): Command { return line.split(" ") .filterIndexed { index, _ -> index % 2 == 1 } .map { it.toInt() } .let { Command(it[0], it[1] - 1, it[2] - 1) } } } } class Day05 { fun numberOfStackes(lines: List<String>) = lines .dropWhile { it.contains("[") } .first() .split(" ") .filter { it.isNotBlank() } .maxOf { it.toInt() } fun populateStackes(lines: List<String>, onCharacterFound: (Int, Char) -> Unit) { lines.filter { it.contains("[") } .map { line -> line.mapIndexed { index, char -> if (char.isLetter()) { val stackNumber = index / 4 val value = line[index] onCharacterFound(stackNumber, value) } } } } } fun main() { val commands = mutableListOf<Command>() val day05 = Day05() fun part1(input: List<String>): String { val numberOfStacks = day05.numberOfStackes(input) val stacks = List(numberOfStacks) { ArrayDeque<Char>() } day05.populateStackes(input) { stackNumber, value -> stacks[stackNumber].addLast(value) } commands.clear() input.filter { it.contains("move") }.map { commands.add(Command.of(it)) } commands.map { step -> repeat(step.count) { stacks[step.to].addFirst(stacks[step.from].removeFirst()) } } return stacks.map { it.first() }.joinToString("") } fun part2(input: List<String>): String { val numberOfStacks = day05.numberOfStackes(input) val stacks = List(numberOfStacks) { ArrayDeque<Char>() } day05.populateStackes(input) { stackNumber, value -> stacks[stackNumber].addLast(value) } commands.clear() commands.map { step -> if (step.count > 1) { val tmp = ArrayDeque<Char>() repeat(step.count) { tmp.addFirst(stacks[step.from].removeFirst()) } repeat(step.count) { stacks[step.to].addFirst(tmp.removeFirst()) } } else { stacks[step.to].addFirst(stacks[step.from].removeFirst()) } } return stacks.map { it.first() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
137fb9a9561f5cbc358b7cfbdaf5562c20d6b10d
2,839
aoc-2022-in-kotlin
Apache License 2.0
kotlin/src/main/kotlin/AoC_Day8.kt
sviams
115,921,582
false
null
object AoC_Day8 { private val ops = mapOf<String, (Int, Int) -> Int>( "inc" to { a, b -> a + b }, "dec" to { a, b -> a - b } ) private val preds = mapOf<String, (Int, Int) -> Boolean>( "<" to { a, b -> a < b }, ">" to { a, b -> a > b }, ">=" to { a, b -> a >= b }, "<=" to { a, b -> a <= b }, "==" to { a, b -> a == b }, "!=" to { a, b -> a != b } ) fun solvePt1(input: List<String>) : Int { val split = input.map { it.split(" ") }.asSequence() return split.fold(split.map { it[0] }.distinct().associateBy({it}, {0})) { regs, line -> if (preds[line[5]]!!(regs[line[4]]!!, line[6].toInt())) { regs.plus(Pair(line[0], ops[line[1]]!!(regs[line[0]]!!, line[2].toInt()))) } else regs }.values.max()!! } fun solvePt2(input: List<String>) : Int { val split = input.map { it.split(" ") }.asSequence() val registers = split.map { it[0] }.distinct().associateBy({it}, {0}).toMutableMap() return split.fold(0) { highest, line -> if (preds[line[5]]!!(registers[line[4]]!!, line[6].toInt())) { registers[line[0]] = ops[line[1]]!!(registers[line[0]]!!, line[2].toInt()) val maxVal = registers.values.max()!! if (maxVal > highest) maxVal else highest } else highest } } }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
1,458
aoc17
MIT License
src/main/kotlin/days/Day8.kt
andilau
573,139,461
false
{"Kotlin": 65955}
package days @AdventOfCodePuzzle( name = "Treetop Tree House", url = "https://adventofcode.com/2022/day/8", date = Date(day = 8, year = 2022) ) class Day8(input: List<String>) : Puzzle { private val trees = input.map { line -> line.map { it.digitToInt() } } override fun partOne(): Int = trees.visibleOutsideTrees() + trees.visibleInsideTrees() override fun partTwo(): Int = (0..trees.lastIndex).flatMap { y -> (0..trees[y].lastIndex).map { x -> Pair(x, y) } }.maxOf { p -> trees.scenicScoreAt(p.first, p.second) } private fun List<List<Int>>.scenicScoreAt(x: Int, y: Int): Int { val line = get(y) val left = (x - 1 downTo 0).map { line[it] } val right = (x + 1..line.lastIndex).map { line[it] } val top = (y - 1 downTo 0).map { this[it][x] } val down = (y + 1..lastIndex).map { this[it][x] } val ls = left.indexOfFirst { it >= line[x] }.let { if (it == -1) left.count() else it + 1 } val rs = right.indexOfFirst { it >= line[x] }.let { if (it == -1) right.count() else it + 1 } val ts = top.indexOfFirst { it >= line[x] }.let { if (it == -1) top.count() else it + 1 } val ds = down.indexOfFirst { it >= line[x] }.let { if (it == -1) down.count() else it + 1 } return ls * rs * ts * ds } private fun List<List<Int>>.visibleOutsideTrees() = 2 * (size + first().count() - 2) private fun List<List<Int>>.visibleInsideTrees() = (1 until this.lastIndex).flatMap { dy -> (1 until this[dy].lastIndex).map { dx -> Pair(dx, dy) } }.count { (x, y) -> this.visibleAt(x, y) } private fun List<List<Int>>.visibleAt(x: Int, y: Int) = (0 until x).map { get(y)[it] }.all { it < get(y)[x] } || (x + 1..get(y).lastIndex).map { get(y)[it] }.all { it < get(y)[x] } || (0 until y).map { this[it][x] }.all { it < get(y)[x] } || (y + 1..lastIndex).map { this[it][x] }.all { it < get(y)[x] } }
0
Kotlin
0
0
da824f8c562d72387940844aff306b22f605db40
2,014
advent-of-code-2022
Creative Commons Zero v1.0 Universal
src/Day04.kt
jsebasct
572,954,137
false
{"Kotlin": 29119}
fun main() { // fun <Int> Pair<Int, Int>.fullyContains(another: Pair<Int, Int>): Boolean { // return another.first <= first && another.second <= second // } fun fullyContains(one: Pair<Int, Int>, another: Pair<Int, Int>): Boolean { return one.first <= another.first && one.second >= another.second } fun overlap(one: Pair<Int, Int>, another: Pair<Int, Int>): Boolean { var res = false val secondRange = another.second..another.second for (i in one.first..one.second) { if (secondRange.contains(i)) { res = true break } } return res } fun parseInput(input: List<String>) = input.map { val (section1, section2) = it.split(",") val (s1p1, s1p2) = section1.split("-") val (s2p1, s2p2) = section2.split("-") //listOf( Pair(s1p1.toInt(), s1p2.toInt()) , Pair(s2p1.toInt(), s2p2.toInt())) Pair(s1p1.toInt(), s1p2.toInt()) to Pair(s2p1.toInt(), s2p2.toInt()) } fun part41(input: List<String>): Int { val sections = parseInput(input) val counter = sections.fold(0) { acc, element -> if ( fullyContains(element.first, element.second ) || fullyContains(element.second, element.first)) { acc + 1 } else acc } return counter } fun part42(input: List<String>): Int { val sections = parseInput(input) val counter = sections.fold(0) { acc, element -> if ( overlap(element.first, element.second ) || overlap(element.second, element.first)) { // println("first: ${element.first} second: ${element.second}") acc + 1 } else acc } return counter // return input.size } // val test1 = fullyContains(Pair(2,8), 3 to 7) // println("test1: $test1") // // val test2 = fullyContains(Pair(4,6), 6 to 6) // println(test2) for (i in 5..7) { println("range: $i") } val input = readInput("Day04_test") println("total: ${part41(input)}") println("Part two") println("total parte 2: ${part42(input)}") // test if implementation meets criteria from the description, like: // val testInput = readInput("Day02_test") // check(part2(testInput) == 45000) }
0
Kotlin
0
0
c4a587d9d98d02b9520a9697d6fc269509b32220
2,389
aoc2022
Apache License 2.0
src/main/kotlin/Day24.kt
clechasseur
267,632,210
false
null
import org.clechasseur.adventofcode2016.Day24Data import org.clechasseur.adventofcode2016.Direction import org.clechasseur.adventofcode2016.Pt import org.clechasseur.adventofcode2016.dij.Dijkstra import org.clechasseur.adventofcode2016.dij.Graph import org.clechasseur.adventofcode2016.math.permutations import kotlin.math.min object Day24 { private val input = Day24Data.input fun part1(): Int { val maze = input.toMaze() val paths = permutations(maze.toVisit.values.toList()) var shortest = Int.MAX_VALUE pathLoop@ for (path in paths) { var visits = path var pathMaze = maze var pos = maze.startPos var steps = 0 while (pathMaze.toVisit.isNotEmpty()) { if (steps > shortest) { continue@pathLoop } val (dist, _) = Dijkstra.build(pathMaze, pos) val next = pathMaze.toVisit.filterValues { it == visits.last() }.keys.single() steps += dist[next]!!.toInt() pos = next pathMaze = pathMaze.afterVisit(next) visits = visits.dropLast(1) } shortest = min(steps, shortest) } return shortest } fun part2(): Int { val maze = input.toMaze() val paths = permutations(maze.toVisit.values.toList()) var shortest = Int.MAX_VALUE pathLoop@ for (path in paths) { var visits = listOf('0') + path var pathMaze = maze var pos = maze.startPos var steps = 0 while (visits.isNotEmpty()) { if (steps > shortest) { continue@pathLoop } val (dist, _) = Dijkstra.build(pathMaze, pos) val next = if (visits.last() != '0') { pathMaze.toVisit.filterValues { it == visits.last() }.keys.single() } else { pathMaze.startPos } steps += dist[next]!!.toInt() pos = next pathMaze = if (visits.last() != '0') { pathMaze.afterVisit(next) } else { pathMaze } visits = visits.dropLast(1) } shortest = min(steps, shortest) } return shortest } private class Maze(val tiles: Map<Pt, Char>) : Graph<Pt> { val startPos = tiles.filterValues { it == '0' }.keys.single() val toVisit = tiles.filterValues { it.toString().toIntOrNull() != null && it != '0' } override fun allPassable(): List<Pt> = tiles.keys.toList() override fun neighbours(node: Pt): List<Pt> = Direction.displacements.mapNotNull { val pt = node + it if (tiles.containsKey(pt)) pt else null } override fun dist(a: Pt, b: Pt): Long = 1L fun afterVisit(pt: Pt): Maze = Maze(tiles.filterKeys { it != pt } + mapOf(pt to '.')) } private fun String.toMaze(): Maze = Maze(lineSequence().withIndex().flatMap { (x, line) -> line.mapIndexed { y, c -> if (c != '#') Pt(x, y) to c else null }.asSequence() }.filterNotNull().toMap()) }
0
Kotlin
0
0
120795d90c47e80bfa2346bd6ab19ab6b7054167
3,282
adventofcode2016
MIT License
src/main/kotlin/aoc2023/day12/day12Solver.kt
Advent-of-Code-Netcompany-Unions
726,531,711
false
{"Kotlin": 94973}
package aoc2023.day12 import lib.* suspend fun main() { setupChallenge().solveChallenge() } fun setupChallenge(): Challenge<List<Pair<String, List<Int>>>> { return setup { day(12) year(2023) //input("example.txt") parser { it.readLines() .map { it.split(" ") } .map { it[0] to it[1].asListOfInts(",") } } partOne { it.sumOf { it.first.replace('.', ' ').countValidCombinations(it.second) } .toString() } partTwo { val unfurled = it.map { it.unfurl() } unfurled.sumOf { it.first.replace('.', ' ').countValidCombinations(it.second) } .toString() } } } fun Pair<String, List<Int>>.unfurl(): Pair<String, List<Int>> { val newString = StringBuilder(this.first) repeat(4) { newString.append('?') newString.append(this.first) } return newString.toString() to List(5) { this.second }.flatten() } fun String.countValidCombinations(numDamagedSprings: List<Int>): Long { val damagedSpringsToFind = numDamagedSprings.sum() - this.count { it == '#' } val res = this.countValidPlacements(numDamagedSprings, damagedSpringsToFind) //println("Found $res solutions...") return res!! } val solutions = mutableMapOf<String, Long?>() fun String.countValidPlacements(groupSizes: List<Int>, toPlace: Int): Long? { val myKey = groupSizes.fold(this) {a, i -> "$a,$i" } if(solutions.containsKey(myKey)) { return solutions[myKey] } val targetGroupNumber = groupSizes.size val groups = this.split(" ").filter { it.isNotEmpty() } val groupPotential = this.count { it == '?' } - toPlace if (groups.size + groupPotential < targetGroupNumber) { return null } if (toPlace == 0) { val isValid = this.replace('?', ' ').verify(groupSizes) return if (isValid) 1 else null } val placements = mutableListOf<Pair<String, List<Int>>>() var i = 0 while (i < this.length) { if (this[i] == '?') { val prefix = this.substring(0 until i).replace('?', ' ') + "#" val groupsMatched = prefix.verifyPrefix(groupSizes) if(groupsMatched < 0) { break } val candidate = prefix.split(" ").last { it.isNotEmpty() } + this.substring(minOf(i + 1, this.length) until this.length) val verificationIndex = candidate.indexOf(' ') val toVerify = if (verificationIndex > 0) candidate.substring(0, verificationIndex) else candidate if (toVerify.verifyCurrentGroup(groupSizes[groupsMatched])) { placements.add(candidate to groupSizes.drop(groupsMatched)) } } i++ } var sum = 0L placements.forEach{ val res = it.first.countValidPlacements(it.second, toPlace - 1) val key = it.second.fold(it.first) {a, i -> "$a,$i" } solutions[key] = res sum += res ?: 0L } return sum } fun String.verifyPrefix(groupSizes: List<Int>): Int { val groups = this.split(" ").filter { it.isNotEmpty() }.dropLast(1) if (groups.isEmpty()) { return 0 } if (groups.size > groupSizes.size) { return -1 } groups.forEachIndexed { index, s -> if (s.length != groupSizes[index]) { return -1 } } return groups.size } fun String.verifyCurrentGroup(targetSize: Int): Boolean { val groups = this.split(" ").filter { it.isNotEmpty() } val group = groups.last() if (group.contains('#')) { if (group.length < targetSize || group.split("?").first().length > targetSize) { return false } } return true } fun String.verify(groupSizes: List<Int>): Boolean { val groups = this.split(" ").filter { it.isNotEmpty() }.map { it.length } return groups.zip(groupSizes).all { it.first == it.second } }
0
Kotlin
0
0
a77584ee012d5b1b0d28501ae42d7b10d28bf070
3,988
AoC-2023-DDJ
MIT License
src/Day13.kt
thorny-thorny
573,065,588
false
{"Kotlin": 57129}
sealed class PacketNode: Comparable<PacketNode> { data class Number(val value: Int): PacketNode() data class List(val content: kotlin.collections.List<PacketNode>): PacketNode() override fun compareTo(other: PacketNode): Int { if (this is Number && other is Number) { return value.compareTo(other.value) } val (thisList, otherList) = listOf(this, other).map { when (it) { is List -> it else -> List(listOf(it)) } } return (0..maxOf(thisList.content.lastIndex, otherList.content.lastIndex)).firstNotNullOfOrNull { val first = thisList.content.getOrNull(it) ?: return@firstNotNullOfOrNull -1 val second = otherList.content.getOrNull(it) ?: return@firstNotNullOfOrNull 1 when (val compare = first.compareTo(second)) { 0 -> null else -> compare } } ?: 0 } } fun main() { fun parsePacketNode(iterator: Iterator<Char>): Pair<PacketNode?, Char?> { var char = iterator.next() when (char) { '[' -> { val content = mutableListOf<PacketNode>() do { val (node, carry) = parsePacketNode(iterator) node?.let { content.add(it) } } while (carry != ']') val listCarry = if (iterator.hasNext()) iterator.next() else null return PacketNode.List(content.toList()) to listCarry } ']' -> return null to char else -> { val string = mutableListOf<Char>() while (char in '0'..'9') { string.add(char) char = iterator.next() } return PacketNode.Number(string.joinToString("").toInt()) to char } } } fun parsePacket(line: String): PacketNode { val (node, carry) = parsePacketNode(line.iterator()) if (node == null || carry != null) { throw Exception("Bad packet format") } return node } fun part1(input: List<String>): Int { return input .asSequence() .filter(String::isNotEmpty) .map(::parsePacket) .chunked(2) .withIndex() .filter { it.value.component1() < it.value.component2() } .sumOf { it.index + 1 } } fun part2(input: List<String>): Int { val inputPackets = input .filter(String::isNotEmpty) .map(::parsePacket) val divider1 = PacketNode.List(listOf(PacketNode.List(listOf(PacketNode.Number(2))))) val divider2 = PacketNode.List(listOf(PacketNode.List(listOf(PacketNode.Number(6))))) val packets = (inputPackets + divider1 + divider2).sorted() return (packets.indexOf(divider1) + 1) * (packets.indexOf(divider2) + 1) } val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
843869d19d5457dc972c98a9a4d48b690fa094a6
3,170
aoc-2022
Apache License 2.0
src/Day13.kt
cypressious
572,916,585
false
{"Kotlin": 40281}
fun main() { data class Point(val x: Int, val y: Int) data class Fold(val horizontal: Boolean, val value: Int) fun parse(input: List<String>): List<CharArray> { val points = input .takeWhile { it.isNotBlank() } .map { it.split(",").map(String::toInt).let { (x, y) -> Point(x, y) } } val width = points.maxOf { it.x } + 1 val height = points.maxOf { it.y } + 1 val grid = List(height) { CharArray(width) { '.' } } for ((x, y) in points) { grid[y][x] = '#' } return grid } fun parseFolds(input: List<String>) = input .takeLastWhile { it.startsWith("fold") } .map { it .substringAfter("along ") .split("=") .let { (dir, value) -> Fold(dir == "x", value.toInt()) } } fun fold(grid: List<CharArray>, fold: Fold): List<CharArray> { val height = if (fold.horizontal) grid.size else grid.size / 2 val width = if (fold.horizontal) grid[0].size / 2 else grid[0].size val folded = List(height) { CharArray(width) { '.' } } for (y in grid.indices) { for (x in grid[y].indices) { if (grid[y][x] == '.') continue if (fold.horizontal && x == fold.value) continue if (!fold.horizontal && y == fold.value) continue if (fold.horizontal && x > fold.value) { folded[y][grid[y].lastIndex - x] = '#' } else if (!fold.horizontal && y > fold.value) { folded[grid.lastIndex - y][x] = '#' } else { folded[y][x] = '#' } } } return folded } fun part1(input: List<String>): Int { val grid = parse(input) val folds = parseFolds(input) val folded = fold(grid, folds.first()) return folded.sumOf { it.count { c -> c == '#' } } } fun part2(input: List<String>): Int { val grid = parse(input) val folds = parseFolds(input) val folded = folds.fold(grid) { acc, fold -> fold(acc, fold) } println(folded.joinToString("\n") { it.joinToString("") }) return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 17) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
169fb9307a34b56c39578e3ee2cca038802bc046
2,518
AdventOfCode2021
Apache License 2.0
src/main/kotlin/day22/Day22.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day22 import java.io.File private const val OFF = false private const val ON = true typealias Cube = Triple<Int, Int, Int> data class RebootStep(val x: IntRange, val y: IntRange, val z: IntRange, val state: Boolean) data class LitRegion(val x: IntRange, val y: IntRange, val z: IntRange) { private fun isEmptyRegion(): Boolean = x.isEmpty() || y.isEmpty() || z.isEmpty() private fun overlapsWith(other: LitRegion): Boolean = TODO() fun subtract(other: LitRegion): List<LitRegion> { if (other.isEmptyRegion() || !overlapsWith(other)) return listOf(this) else { TODO() } } } fun parseInput(lines: List<String>): List<RebootStep> { fun parseRange(range: String): IntRange { val (n1, n2) = range.split("..").map(String::toInt) return n1..n2 } fun extractRanges(ranges: String): Triple<IntRange, IntRange, IntRange> { val (x, y, z) = ranges.split(",").map { parseRange(it.drop(2)) } return Triple(x, y, z) } return lines.map { line -> when { line.startsWith("on") -> { val (x, y, z) = extractRanges(line.removePrefix("on ")) RebootStep(x, y, z, ON) } line.startsWith("off") -> { val (x, y, z) = extractRanges(line.removePrefix("off ")) RebootStep(x, y, z, OFF) } else -> TODO() } } } fun countCubesOnRestricted(steps: List<RebootStep>): Int { fun isOutOfRange(step: RebootStep): Boolean = listOf(step.x, step.y, step.z).any { it.first < -50 || it.last > 50 } val cubes = Array(101) { Array(101) { Array(101) { OFF } } } for (step in steps.filterNot(::isOutOfRange)) { step.x.forEach { x -> step.y.forEach { y -> step.z.forEach { z -> cubes[x + 50][y + 50][z + 50] = step.state } } } } return cubes.sumOf { it.sumOf { it.count { it == ON } } } } fun countCubesUnbounded(steps: List<RebootStep>): Long { val cubesOn = HashSet<Cube>() for (step in steps) { println(step) val cubes = step.x.flatMap { x -> step.y.flatMap { y -> step.z.map { z -> Cube(x, y, z) } } } if (step.state == ON) cubesOn.addAll(cubes) else cubesOn.removeAll(cubes) } return cubesOn.sumOf { 1L } } fun main() { File("./input/day22.txt").useLines { lines -> val rebootSteps = parseInput(lines.toList()) println(countCubesOnRestricted(rebootSteps)) } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
2,356
advent-of-code-2021
MIT License
src/Day08.kt
jinie
572,223,871
false
{"Kotlin": 76283}
class Day08 { private fun linesOfSight(map: List<List<Int>>, x: Int, y: Int) = sequenceOf( sequenceOf((x - 1 downTo 0), (x + 1 until map[0].size)).map { it.map { x -> x to y } }, sequenceOf((y - 1 downTo 0), (y + 1 until map.size)).map { it.map { y -> x to y } } ).flatten().map { it.map { (x, y) -> map[y][x] } } private fun List<Int>.countVisible(h: Int) = indexOfFirst { it >= h }.let { if (it == -1) size else it + 1 } fun part1(map: List<List<Int>>): Int{ with(map.flatMapIndexed { y, l -> l.mapIndexed { x, h -> Triple(x, y, h) } }) { return count { (x, y, h) -> linesOfSight(map, x, y).any { it.all { oh -> oh < h } } } } } fun part2(map: List<List<Int>>): Int { with(map.flatMapIndexed { y, l -> l.mapIndexed { x, h -> Triple(x, y, h) } }) { return maxOf { (x, y, h) -> linesOfSight(map, x, y).map { it.countVisible(h) }.reduce(Int::times) } } } } fun main() { val d8 = Day08() val testMap = readInput("Day08_test").map { it.map(Char::digitToInt) } check(d8.part1(testMap) == 21) measureTimeMillisPrint { val map = readInput("Day08").map { it.map(Char::digitToInt)} println(d8.part1(map)) println(d8.part2(map)) } }
0
Kotlin
0
0
4b994515004705505ac63152835249b4bc7b601a
1,273
aoc-22-kotlin
Apache License 2.0
src/Day04.kt
Longtainbin
573,466,419
false
{"Kotlin": 22711}
fun main() { val input = readInput("inputDay04") fun part1(input: List<String>): Int { return processPart1(input) } fun part2(input: List<String>): Int { return processPart2(input) } println(part1(input)) println(part2(input)) } // For part_1 private fun processPart1(input: List<String>): Int { var sum = 0 input.forEach { val pairArray = transform(it) if (pairArray[0].contains(pairArray[1]) || pairArray[1].contains(pairArray[0])) { sum++ } } return sum } /** * if this fully contain other, return true; * otherwise return false */ fun Pair<Int, Int>.contains(other: Pair<Int, Int>): Boolean { return (this.first <= other.first) && (this.second >= other.second) } // For part_2 private fun processPart2(input: List<String>): Int { var sum = 0 input.forEach { val pairArray = transform(it) if (pairArray[0].overlap(pairArray[1])) { sum++ } } return sum } /** * if two pairs do overlap ,return true; * otherwise return false */ fun Pair<Int, Int>.overlap(other: Pair<Int, Int>): Boolean { return this.contains(other) || (this.first in other.first..other.second) || (this.second in other.first..other.second) } // common function private fun transform(str: String): Array<Pair<Int, Int>> { val strList = str.split(',') var temp = strList[0].split('-') val a = Pair<Int, Int>(temp[0].toInt(), temp[1].toInt()) temp = strList[1].split('-') val b = Pair<Int, Int>(temp[0].toInt(), temp[1].toInt()) return arrayOf(a, b) }
0
Kotlin
0
0
48ef88b2e131ba2a5b17ab80a0bf6a641e46891b
1,619
advent-of-code-2022
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2021/day21/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day21 import com.kingsleyadio.adventofcode.util.readInput fun part1(p1: Int, p2: Int): Int { val scores = intArrayOf(0, 0) val positions = intArrayOf(p1, p2) var rolls = 0 var player = 0 while (true) { val rolled = ++rolls + ++rolls + ++rolls positions[player] = (positions[player] + rolled - 1) % 10 + 1 scores[player] += positions[player] player = ++player % 2 val (min, max) = scores.sorted() if (max >= 1000) return min * rolls } } fun part2(p1: Int, p2: Int): Long { fun generateDieRolls() = sequence { for (i in 1..3) for (j in 1..3) for (k in 1..3) { yield(i + j + k) } } // ¯\_(ツ)_/¯ val cache = hashMapOf<String, LongArray>() fun memo( positions: List<Int>, scores: List<Int>, player: Int, roll: Int, func: (List<Int>, List<Int>, Int, Int) -> LongArray ): LongArray { val key = "${positions.hashCode()}-${scores.hashCode()}-$player-$roll" return cache.getOrPut(key) { func(positions, scores, player, roll) } } fun play(positions: List<Int>, scores: List<Int>, player: Int, roll: Int): LongArray { val position = (positions[player] + roll - 1) % 10 + 1 val score = scores[player] + position if (score >= 21) return longArrayOf(1L - player, player.toLong()) val newPositions = if (player == 0) listOf(position, positions[1]) else listOf(positions[0], position) val newScores = if (player == 0) listOf(score, scores[1]) else listOf(scores[0], score) val newPlayer = (player + 1) % 2 return generateDieRolls().fold(longArrayOf(0, 0)) { (p1, p2), rolled -> val (newP1, newP2) = memo(newPositions, newScores, newPlayer, rolled, ::play) longArrayOf(p1 + newP1, p2 + newP2) } } val startPositions = listOf(p1, p2) val startScores = listOf(0, 0) val wins = generateDieRolls().fold(longArrayOf(0, 0)) { (p1, p2), rolled -> val (newP1, newP2) = memo(startPositions, startScores, 0, rolled, ::play) longArrayOf(p1 + newP1, p2 + newP2) } return wins.maxOf { it } } fun main() { val (p1, p2) = readInput(2021, 21).readLines().map { it.substringAfterLast(" ").toInt() } println(part1(p1, p2)) println(part2(p1, p2)) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
2,397
adventofcode
Apache License 2.0
src/day02/day02.kt
LostMekka
574,697,945
false
{"Kotlin": 92218}
package day02 import day02.Hand.Paper import day02.Hand.Rock import day02.Hand.Scissors import util.readInput import util.shouldBe fun main() { val day = 2 val testInput = readInput(day, testInput = true).parseInput() part1(testInput) shouldBe 15 part2(testInput) shouldBe 12 val input = readInput(day).parseInput() println("output for part1: ${part1(input)}") println("output for part2: ${part2(input)}") } private enum class Hand(val score: Int) { Rock(1), Paper(2), Scissors(3), } private val Hand.weakness get() = when (this) { Rock -> Paper Paper -> Scissors Scissors -> Rock } private val Hand.strength get() = when (this) { Rock -> Scissors Paper -> Rock Scissors -> Paper } private infix fun Hand.scoreAgainst(other: Hand) = when (other) { this -> 3 this.weakness -> 0 else -> 6 } private class Input( val lines: List<Pair<String, String>>, ) private fun List<String>.parseInput(): Input { return Input( map { line -> val (letter1, letter2) = line.split(" ") letter1 to letter2 } ) } private fun String.toHand() = when (this) { "A" -> Rock "B" -> Paper "C" -> Scissors "X" -> Rock "Y" -> Paper "Z" -> Scissors else -> error("oops") } private fun part1(input: Input): Int { return input.lines.sumOf { (letter1, letter2) -> val opponentHand = letter1.toHand() val ownHand = letter2.toHand() ownHand.score + ownHand.scoreAgainst(opponentHand) } } private fun part2(input: Input): Int { return input.lines.sumOf { (letter1, letter2) -> val opponentHand = letter1.toHand() val ownHand = when (letter2) { "X" -> opponentHand.strength "Y" -> opponentHand "Z" -> opponentHand.weakness else -> error("oops") } ownHand.score + ownHand.scoreAgainst(opponentHand) } }
0
Kotlin
0
0
58d92387825cf6b3d6b7567a9e6578684963b578
2,048
advent-of-code-2022
Apache License 2.0
src/Day14.kt
floblaf
572,892,347
false
{"Kotlin": 28107}
import kotlin.math.max import kotlin.math.min fun main() { fun Grid.add(x: Int, y: Int, material: Grid.Material) { if (content[x] == null) { content[x] = mutableMapOf() } content[x]!![y] = material } fun Grid.findDeepestRock(): Int { return content.values.maxOf { it.keys.max() } } fun Grid.nextPosition(x: Int, y: Int): Pair<Int, Int>? { return listOf(0, -1, +1) .map { x + it } .firstOrNull { content[it]?.get(y + 1) == null } ?.let { it to y + 1 } } fun parseGrid(): Grid { val grid = Grid() readInput("Day14") .map { line -> line .split("->") .map { it.trim() } .windowed(2) } .flatten() .forEach { (start, end) -> val (xStart, yStart) = start.split(",").map { it.toInt() } val (xEnd, yEnd) = end.split(",").map { it.toInt() } if (xStart == xEnd) { for (i in min(yStart, yEnd)..max(yStart, yEnd)) { grid.add(xStart, i, Grid.Material.ROCK) } } else if (yStart == yEnd) { for (i in min(xStart, xEnd)..max(xStart, xEnd)) { grid.add(i, yStart, Grid.Material.ROCK) } } else { throw IllegalStateException() } } return grid } fun part1(grid: Grid): Int { val yMax = grid.findDeepestRock() infinite@ while (true) { var xSand = 500 var ySand = 0 while (true) { val next = grid.nextPosition(xSand, ySand) ?: break if (ySand == yMax) break@infinite xSand = next.first ySand = next.second } grid.add(xSand, ySand, Grid.Material.SAND) } return grid.content.values.sumOf { it.values.count { it == Grid.Material.SAND } } } fun part2(grid: Grid): Int { val yMax = grid.findDeepestRock() + 2 while (true) { if (grid.content[500]?.get(0) == Grid.Material.SAND) break var xSand = 500 var ySand = 0 while (true) { if (ySand == yMax - 1) break val next = grid.nextPosition(xSand, ySand) ?: break xSand = next.first ySand = next.second } grid.add(xSand, ySand, Grid.Material.SAND) } return grid.content.values.sumOf { it.values.count { it == Grid.Material.SAND } } } println(part1(parseGrid())) println(part2(parseGrid())) } data class Grid( val content: MutableMap<Int, MutableMap<Int, Material>> = mutableMapOf() ) { enum class Material { ROCK, SAND } }
0
Kotlin
0
0
a541b14e8cb401390ebdf575a057e19c6caa7c2a
2,945
advent-of-code-2022
Apache License 2.0
src/Day02.kt
andydenk
573,909,669
false
{"Kotlin": 24096}
fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<String>): Int { return input .map { shapePair(it) } .map { (opponent, protagonist) -> Round(opponent, protagonist) } .sumOf { it.protagonistTotalScore() } } private fun part2(input: List<String>): Int { return input .map { shapeAndOutcome(it) } .map { (opponentShape, outcome) -> opponentShape to findNeededShape(opponentShape, outcome) } .map { (opponent, protagonist) -> Round(opponent, protagonist) } .sumOf { it.protagonistTotalScore() } } private fun findNeededShape(opponentShape: Shape, outcomeNeeded: Outcome): Shape { return when (outcomeNeeded) { Outcome.WIN -> opponentShape.beatenBy() Outcome.DRAW -> opponentShape Outcome.LOSS -> opponentShape.beats() } } private fun shapeFor(input: String) = when (input) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> throw IllegalStateException("Invalid input") } private fun shapePair(input: String): Pair<Shape, Shape> { val choices = input.split(" ") if (choices.size != 2) { throw java.lang.IllegalStateException("Invalid amount of choices") } return shapeFor(choices[0]) to shapeFor(choices[1]) } private fun shapeAndOutcome(input: String): Pair<Shape, Outcome> { val choices = input.split(" ") if (choices.size != 2) { throw java.lang.IllegalStateException("Invalid amount of choices") } return shapeFor(choices[0]) to Outcome.forInput(choices[1]) } private class Round(private val opponent: Shape, private val protagonist: Shape) { fun protagonistTotalScore(): Int { return protagonist.scoreAgainst(opponent) + protagonist.baseScore } } private sealed class Shape(val baseScore: Int) { abstract fun beats(): Shape abstract fun beatenBy(): Shape fun scoreAgainst(other: Shape): Int { val outcome = when (other) { beats() -> Outcome.WIN beatenBy() -> Outcome.LOSS this -> Outcome.DRAW else -> throw IllegalStateException("Invalid Shape Comparison") } return outcome.score } } private object Rock : Shape(1) { override fun beats(): Shape = Scissors override fun beatenBy(): Shape = Paper } private object Paper : Shape(2) { override fun beats(): Shape = Rock override fun beatenBy(): Shape = Scissors } private object Scissors : Shape(3) { override fun beats(): Shape = Paper override fun beatenBy(): Shape = Rock } private enum class Outcome(val score: Int) { WIN(6), DRAW(3), LOSS(0); companion object { fun forInput(input: String): Outcome = when (input) { "X" -> LOSS "Y" -> DRAW "Z" -> WIN else -> throw IllegalStateException("Invalid Objective") } } }
0
Kotlin
0
0
1b547d59b1dc55d515fe8ca8e88df05ea4c4ded1
3,169
advent-of-code-2022
Apache License 2.0
src/main/kotlin/codes/jakob/aoc/solution/Day14.kt
The-Self-Taught-Software-Engineer
433,875,929
false
{"Kotlin": 56277}
package codes.jakob.aoc.solution object Day14 : Solution() { override fun solvePart1(input: String): Any { val (polymerTemplate: List<Char>, elementInsertionRules: Map<Pair<Char, Char>, Char>) = parseInput(input) val processedElementPairFrequencies: Map<Pair<Char, Char>, ULong> = processPolymerTemplate(polymerTemplate, elementInsertionRules, 10) return calculateMostLeastCommonDifference(processedElementPairFrequencies) } override fun solvePart2(input: String): Any { val (polymerTemplate: List<Char>, pairInsertionRules: Map<Pair<Char, Char>, Char>) = parseInput(input) val processedElementPairFrequencies: Map<Pair<Char, Char>, ULong> = processPolymerTemplate(polymerTemplate, pairInsertionRules, 40) return calculateMostLeastCommonDifference(processedElementPairFrequencies) } private fun processPolymerTemplate( polymerTemplate: List<Char>, elementInsertionRules: Map<Pair<Char, Char>, Char>, times: Int, ): Map<Pair<Char, Char>, ULong> { val elementPairCounts: Map<Pair<Char, Char>, ULong> = polymerTemplate .windowed(2) .map { it.first() to it.last() } .countBy { it } .mapValues { it.value.toULong() } val processedElementPairCounts: MutableMap<Pair<Char, Char>, ULong> = (1..times).fold(elementPairCounts) { accumulator: Map<Pair<Char, Char>, ULong>, _ -> val newElementPairCounts: MutableMap<Pair<Char, Char>, ULong> = mutableMapOf<Pair<Char, Char>, ULong>().withDefault { 0UL } for ((elementPair: Pair<Char, Char>, count: ULong) in accumulator.entries) { val insertElement: Char = elementInsertionRules[elementPair] ?: continue val firstInsertion: Pair<Char, Char> = Pair(elementPair.first, insertElement) val secondInsertion: Pair<Char, Char> = Pair(insertElement, elementPair.second) newElementPairCounts[firstInsertion] = newElementPairCounts.getValue(firstInsertion) + count newElementPairCounts[secondInsertion] = newElementPairCounts.getValue(secondInsertion) + count } return@fold newElementPairCounts }.toMutableMap() // The count of the first and last element of the polymer template is missing still val missingPair: Pair<Char, Char> = Pair(polymerTemplate.last(), polymerTemplate.first()) processedElementPairCounts[missingPair] = (processedElementPairCounts[missingPair] ?: 0UL) + 1UL return processedElementPairCounts } private fun calculateMostLeastCommonDifference(elementPairCounts: Map<Pair<Char, Char>, ULong>): ULong { val elementCounts: Map<Char, ULong> = elementPairCounts.entries .fold(mapOf()) { accumulator: Map<Char, ULong>, entry: Map.Entry<Pair<Char, Char>, ULong> -> val frequencies: MutableMap<Char, ULong> = accumulator.toMutableMap().withDefault { 0UL } val (firstElement: Char, secondElement: Char) = entry.key frequencies[firstElement] = frequencies.getValue(firstElement) + entry.value frequencies[secondElement] = frequencies.getValue(secondElement) + entry.value return@fold frequencies } .mapValues { it.value / 2UL } // Since every element is contained in two pairs val mostCommonElement: Map.Entry<Char, ULong> = elementCounts.maxByOrNull { it.value }!! val leastCommonElement: Map.Entry<Char, ULong> = elementCounts.minByOrNull { it.value }!! return (mostCommonElement.value - leastCommonElement.value) } private fun parseInput(input: String): Pair<List<Char>, Map<Pair<Char, Char>, Char>> { val (templateLine: String, rulesLines: String) = input.split("\n\n") val template: List<Char> = templateLine.split("").filter { it.isNotBlank() }.map { it.toSingleChar() } val rules: Map<Pair<Char, Char>, Char> = rulesLines.splitMultiline().map { rule -> val (pair: String, result: String) = rule.split(" -> ") val (first: String, second: String) = pair.split("").filter { it.isNotBlank() } return@map Pair(first.toSingleChar(), second.toSingleChar()) to result.toSingleChar() }.toMap() return template to rules } } fun main() { Day14.solve() }
0
Kotlin
0
6
d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c
4,481
advent-of-code-2021
MIT License
src/day04/Day04.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day04 import readInput import readTestInput private fun List<String>.asElfPairSequence(): Sequence<Pair<String, String>> = this .asSequence() .map { elfPair -> val (firstElf, secondElf) = elfPair.split(",") firstElf to secondElf } private fun Sequence<Pair<String, String>>.toSectionRangePair(): Sequence<Pair<IntRange, IntRange>> = this .map { (firstElf, secondElf) -> firstElf.toSectionRange() to secondElf.toSectionRange() } private fun String.toSectionRange(): IntRange { val rangeValues = split("-").map { it.toInt() } return rangeValues[0]..rangeValues[1] } private fun IntRange.contains(other: IntRange): Boolean = this.first <= other.first && this.last >= other.last private fun IntRange.overlaps(other: IntRange): Boolean = this.last >= other.first && this.first <= other.last private fun part1(input: List<String>): Int { return input .asElfPairSequence() .toSectionRangePair() .count { (sectionRangeA, sectionRangeB) -> sectionRangeA.contains(sectionRangeB) || sectionRangeB.contains(sectionRangeA) } } private fun part2(input: List<String>): Int { return input .asElfPairSequence() .toSectionRangePair() .count { (sectionRangeA, sectionRangeB) -> sectionRangeA.overlaps(sectionRangeB) } } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day04") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
1,649
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day03.kt
MichalChomo
572,214,942
false
{"Kotlin": 56758}
package eu.michalchomo.adventofcode.year2023 import eu.michalchomo.adventofcode.Day import eu.michalchomo.adventofcode.main object Day03 : Day { override val number: Int = 3 override fun part1(input: List<String>): String = input.addFirstAndLastBlank() .windowed(3, 1) .sumOf { window -> val upperLine = window[0] val currentLine = window[1] val bottomLine = window[2] val indexedNumbers = currentLine.indices.fold(mutableListOf<Pair<Int, String>>()) { acc, index -> if (currentLine[index].isDigit() && (index == 0 || !currentLine[index - 1].isDigit())) { val number = currentLine.substring(index).takeWhile { it.isDigit() } acc.add(index to number) } acc } indexedNumbers.filter { (index, number) -> val startIndex = (index - 1).coerceAtLeast(0) val endIndex = (index + number.length + 1).coerceAtMost(currentLine.length) upperLine.substring(startIndex, endIndex).any { it.isSymbol() } || // Look at the start of line only if the number is not at the start (index > 0 && currentLine[startIndex].isSymbol()) || // Look at the end of line only if the number is not at the end (index < (currentLine.length - number.length) && currentLine[endIndex - 1].isSymbol()) || bottomLine.substring(startIndex, endIndex).any { it.isSymbol() } } .sumOf { it.second.toInt() } }.toString() override fun part2(input: List<String>): String = input.addFirstAndLastBlank() .windowed(3, 1) { window -> val upperLine = window[0] val currentLine = window[1] val bottomLine = window[2] val gearIndices = currentLine.mapIndexedNotNull { index, c -> if (c == '*') index else null } gearIndices.sumOf { index -> val adjacentNumbers = upperLine.findAdjacentNumbersAtIndex(index) + currentLine.findAdjacentNumbersAtIndex(index) + bottomLine.findAdjacentNumbersAtIndex(index) if (adjacentNumbers.size == 2) adjacentNumbers.reduce(Int::times) else 0 } }.sumOf { it }.toString() private fun Char.isSymbol() = this != '.' && !this.isDigit() private fun List<String>.addFirstAndLastBlank() = this.toMutableList() .apply { val dots = generateSequence { '.' }.take(this[0].length).joinToString("") add(0, dots) add(dots) } private fun String.findAdjacentNumbersAtIndex(index: Int): List<Int> = ( (if (index > 0) this.substring(0, index).reversed().takeWhile { it.isDigit() }.reversed() else "") + (this[index].digitToIntOrNull()?.toString() ?: ".") + (if (index < this.length - 1) this.substring(index + 1).takeWhile { it.isDigit() } else "") ) .split('.').filter { it.isNotEmpty() }.map { it.toInt() } } fun main() { main(Day03) }
0
Kotlin
0
0
a95d478aee72034321fdf37930722c23b246dd6b
3,246
advent-of-code
Apache License 2.0
src/Day13.kt
wujingwe
574,096,169
false
null
import java.util.Stack object Day13 { sealed class Node { object LEFT : Node() class Sequence(val elements: List<Node>) : Node() class Digit(val element: Int) : Node() operator fun compareTo(other: Node): Int { if (this is Digit && other is Digit) { return this.element - other.element } else if (this is Sequence && other is Digit) { return compareTo(Sequence(listOf(other))) } else if (this is Digit && other is Sequence) { return Sequence(listOf(this)).compareTo(other) } else { // Both list val left = this as Sequence val right = other as Sequence var i = 0 while (i < left.elements.size && i < right.elements.size) { val ret = left.elements[i].compareTo(right.elements[i]) if (ret != 0) { return ret } i++ } return if (left.elements.size == right.elements.size) { 0 } else if (i >= left.elements.size) { -1 } else { // i >= right.elements.size 1 } } } } private fun parse(s: String): Node.Sequence { val res = mutableListOf<Node>() val stack = Stack<Node>() var i = 0 while (i < s.length) { when (val c = s[i]) { '[' -> stack.push(Node.LEFT) ']' -> { val list = mutableListOf<Node>() while (stack.peek() != Node.LEFT) { val node = stack.pop() list.add(node) } stack.pop() // pop '[' stack.push(Node.Sequence(list.reversed())) } ',' -> Unit // ignore else -> { var digit = c - '0' while (i < s.length - 1 && s[i + 1].isDigit()) { digit = digit * 10 + (s[i + 1] - '0') i++ } stack.push(Node.Digit(digit)) } } i++ } while (stack.isNotEmpty()) { res.add(stack.pop()) } return Node.Sequence(res.reversed()) } fun part1(inputs: String): Int { return inputs.split("\n\n") .withIndex() .filter { (_, s) -> val (a, b) = s.split("\n") val left = parse(a) val right = parse(b) left < right }.sumOf { it.index + 1 } } fun part2(inputs: String): Int { val list = inputs.split("\n") .filter { it.isNotEmpty() } .map { parse(it) } .toMutableList() val two = Node.Sequence(listOf(Node.Sequence(listOf(Node.Digit(2))))) list.add(two) val six = Node.Sequence(listOf(Node.Sequence(listOf(Node.Digit(6))))) list.add(six) list.sortWith { a, b -> a.compareTo(b) } val v1 = list.indexOf(two) val v2 = list.indexOf(six) return (v1 + 1) * (v2 + 1) } } fun main() { fun part1(inputs: String): Int { return Day13.part1(inputs) } fun part2(inputs: String): Int { return Day13.part2(inputs) } val testInput = readText("../data/Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readText("../data/Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a5777a67d234e33dde43589602dc248bc6411aee
3,723
advent-of-code-kotlin-2022
Apache License 2.0
src/Day09.kt
AxelUser
572,845,434
false
{"Kotlin": 29744}
import kotlin.math.abs fun main() { val diagonal = listOf(1, 1, -1, -1, 1) val straight = listOf(0, 1, 0, -1, 0) fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> = first + other.first to second + other.second fun Pair<Int, Int>.distanceTo(other: Pair<Int, Int>): Int = maxOf(abs(first - other.first), abs(second - other.second)) fun Pair<Int, Int>.closestTo(other: Pair<Int, Int>): Pair<Int, Int> = (if (first != other.first && second != other.second) diagonal else straight) .windowed(2) .map { (row, col) -> this.plus(row to col) } .single { it.distanceTo(other) == 1 } val deltaMap = mapOf( 'R' to (0 to 1), 'L' to (0 to -1), 'U' to (1 to 0), 'D' to (-1 to 0) ) fun List<String>.solve(k: Int): Int { val knots = Array(k) { 0 to 0 } val visited = mutableSetOf(0 to 0) for ((deltaH, steps) in this.map { it.split(' ').let { (d, s) -> deltaMap[d[0]]!! to s.toInt() } }) { repeat(steps) { knots[0] = knots[0].plus(deltaH) for (ki in 1..knots.lastIndex) { if (knots[ki].distanceTo(knots[ki - 1]) < 2) break knots[ki] = knots[ki].closestTo(knots[ki - 1]) } visited.add(knots.last()) } } return visited.size } fun part1(input: List<String>): Int { return input.solve(2) } fun part2(input: List<String>): Int { return input.solve(10) } var input = readInput("Day09_test") check(part1(input) == 13) check(part2(input) == 1) input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
042e559f80b33694afba08b8de320a7072e18c4e
1,758
aoc-2022
Apache License 2.0
src/Day16-wip.kt
p357k4
573,068,508
false
{"Kotlin": 59696}
fun main() { fun part1(input: List<String>): Int { val data = input.map { line -> val valve = line.substringAfter("Valve ").substringBefore(" ") val rate = line.substringAfter("rate=").substringBefore(";").toInt() val valves = if (line.contains("leads to valve ")) { line.substringAfter("leads to valve ").split(',').map { it.trim() } } else { line.substringAfter("lead to valves ").split(',').map { it.trim() } } Pair(valve to valves, valve to rate) } val rate = data.associate { it.second } val valves = data.associate { it.first } val zeros = rate.filter { it.value == 0 }.map { it.key } var best = listOf<String>() var bestScore = 0 fun findNext(remaining : Int, current : String, maximum : MutableMap<String, Int>, visited : List<String>, opened: List<String>, cached : MutableMap<String, Int>) { if (opened.contains(current)) { return } if (visited.contains(current)) { return } val delta = remaining * rate.getValue(current) if (delta > maximum.getOrDefault(current, 0)) { maximum[current] = delta cached[current] = remaining } for(next in valves.getValue(current)) { findNext(remaining - 1, next, maximum, visited + current, opened, cached) } } fun inspect(remaining: Int, current: String, opened: List<String>, released: Int): Int { if (remaining == 0 || zeros.size + opened.size == valves.size) { if (released > bestScore) { bestScore = released best = opened } return released } val maximum = mutableMapOf<String, Int>() val cached = mutableMapOf<String, Int>() findNext(remaining, current, maximum, listOf(), opened, cached) val nextValve = maximum.maxBy { entry -> entry.value }.key val nextRemaining = cached.getValue(nextValve) return inspect(nextRemaining, nextValve, opened + current, released + maximum.getValue(nextValve)) } val result = inspect(29, "AA", listOf(), 0) return result } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInputExample = readInput("Day16_example") check(part1(testInputExample) == 1651) check(part2(testInputExample) == 0) val testInput = readInput("Day16_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
b9047b77d37de53be4243478749e9ee3af5b0fac
2,790
aoc-2022-in-kotlin
Apache License 2.0
src/Day07.kt
uekemp
575,483,293
false
{"Kotlin": 69253}
sealed class FileSystemItem { abstract val name: String } class Directory(val parent: Directory?, override val name: String) : FileSystemItem() { val children = mutableListOf<FileSystemItem>() var size = 0L fun add(item: FileSystemItem) = children.add(item) fun findDirectory(name: String): Directory? { return children.find { item -> item is Directory && item.name == name } as Directory? } fun traverseDirectories(visitor: (Directory) -> Unit) { if (parent == null) { visitor(this) } children.filterIsInstance<Directory>().forEach { directory -> visitor(directory) directory.traverseDirectories(visitor) } } fun computeSize(): Directory { children.forEach { child -> size += when (child) { is Directory -> { child.computeSize().size } is File -> { child.size } } } return this } override fun toString(): String { return "$name (dir, size=$size)" } } class File(override val name: String, val size: Long) : FileSystemItem() { override fun toString(): String { return "$name (file, size=$size)" } } fun parseTree(input: List<String>): Directory { val root = Directory(null, "/") var currentDirectory = root input.forEach { line -> when { line.startsWith("$ ls") -> { // ignore } line.startsWith("$ cd /") -> { currentDirectory = root } line.startsWith("$ cd ..") -> { currentDirectory = currentDirectory.parent ?: root } line.startsWith("$ cd ") -> { val (_, _, name) = line.split(" ") currentDirectory = currentDirectory.findDirectory(name) ?: error("Changing to unknown directory") } line.startsWith("dir ") -> { val name = line.substring(4) currentDirectory.add(Directory(currentDirectory, name)) } else -> { val (size, name) = line.split(" ") currentDirectory.add(File(name, size.toLong())) } } } return root } fun printTree(directory: Directory, indent: String = "") { println("$indent- $directory") directory.children.forEach { when (it) { is Directory -> { printTree(it, "$indent ") } is File -> println("$indent - $it") } } } fun main() { fun part1(input: List<String>): Long { val root = parseTree(input).computeSize() // printTree(root) val result = mutableListOf<Directory>() root.traverseDirectories { dir -> if (dir.size <= 100000) result.add(dir) } return result.sumOf { it.size } } fun part2(input: List<String>): Long { val root = parseTree(input).computeSize() val result = mutableListOf<Directory>() val required = 30_000_000 - (70_000_000 - root.size) root.traverseDirectories { dir -> if (dir.size >= required) result.add(dir) } return result.minOf(Directory::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") check(part1(input) == 1723892L) check(part2(input) == 8474158L) }
0
Kotlin
0
0
bc32522d49516f561fb8484c8958107c50819f49
3,515
advent-of-code-kotlin-2022
Apache License 2.0
src/Day07.kt
RobvanderMost-TomTom
572,005,233
false
{"Kotlin": 47682}
data class File( val name: String, val size: Int ) data class Dir( val name: String, val parent: Dir? = null, val files: MutableList<File> = mutableListOf(), val dirs: MutableMap<String, Dir> = mutableMapOf() ) { fun size(): Int = files.sumOf { it.size } + dirs.values.sumOf { it.size() } fun allSizes(): List<Int> = dirs.values.flatMap { it.allSizes() } + size() } fun main() { fun parseFileTree(input: List<String>): Dir { val root = Dir("") var currentDir = root input .map { it.split(" ") } .forEach { check(it.size >= 2) if (it[0] == "$" && it[1] == "cd") { check(it.size == 3) currentDir = if (it[2] == "/") { root } else if (it[2] == "..") { checkNotNull(currentDir.parent) currentDir.parent!! } else { currentDir.dirs[it[2]] ?: throw RuntimeException() } } else if (it[0] == "dir") { if (!currentDir.dirs.containsKey(it[1])) { currentDir.dirs[it[1]] = Dir(it[1], currentDir) } } else if (it[0].toIntOrNull() != null){ currentDir.files.add( File(it[1], it[0].toInt()) ) } } return root } fun part1(input: List<String>): Int { val tree = parseFileTree(input) return tree.allSizes().filter { it < 100000 }.sum() } fun part2(input: List<String>): Int { val tree = parseFileTree(input) val totalDiskSpace = 70000000 val spaceRequired = 30000000 val freeDiskSpace = totalDiskSpace - tree.size() val toFree = spaceRequired - freeDiskSpace check(toFree > 0) return tree.allSizes() .filter { it > toFree }.minOf { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
5
Kotlin
0
0
b7143bceddae5744d24590e2fe330f4e4ba6d81c
2,368
advent-of-code-2022
Apache License 2.0
solutions/src/Day03.kt
khouari1
573,893,634
false
{"Kotlin": 132605, "HTML": 175}
fun main() { fun part1(input: List<String>): Int { return input.map { line -> val individualChars = line.split("") val first = individualChars.subList(0, individualChars.size / 2) val second = individualChars.subList(individualChars.size / 2, individualChars.size - 1) first.intersect(second.toSet()).first() }.sumOf { letterValue(it) } } fun part2(input: List<String>): Int { return input.chunked(3) .map { group -> val first = group[0].asIndividualGroupChars() val second = group[1].asIndividualGroupChars() val third = group[2].asIndividualGroupChars() first.intersect(second.toSet()).intersect(third.toSet()).first() }.sumOf { letterValue(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } private fun letterValue(letter: String): Int { val letterAsChar = letter.single() return if (letterAsChar.isUpperCase()) { letterAsChar - 'A' + 27 } else { letterAsChar - 'a' + 1 } } private fun String.asIndividualGroupChars() = split("").distinct().drop(1)
0
Kotlin
0
1
b00ece4a569561eb7c3ca55edee2496505c0e465
1,445
advent-of-code-22
Apache License 2.0
src/main/kotlin/aoc23/Day03.kt
tahlers
725,424,936
false
{"Kotlin": 65626}
package aoc23 object Day03 { data class Pos(val x: Int, val y: Int) data class Part(val number: Int, val startPos: Pos, val endPos: Pos) { private val xRange = (startPos.x - 1)..(endPos.x + 1) val adjacentPositions = xRange.map { Pos(it, startPos.y - 1) } + listOf(Pos(startPos.x - 1, startPos.y), Pos(endPos.x + 1, endPos.y)) + xRange.map { Pos(it, startPos.y + 1) } } data class Symbol(val symbolChar: Char, val pos: Pos) data class Schematic(val parts: List<Part> = emptyList(), val symbols: Set<Symbol> = emptySet()) private val numbersRegex = """(\d+)""".toRegex() private val symbolRegex = """[^0-9.]""".toRegex() fun calculateSumAdjacentToSymbols(input: String): Int { val schematic = parseSchematic(input) val adjacentParts = findAdjacentToSymbols(schematic) return adjacentParts.sumOf { it.number } } fun calculateSumOfGearRatios(input: String): Int { val schematic = parseSchematic(input) val gearCandidates = schematic.symbols.filter { it.symbolChar == '*' } val gearRatios = gearCandidates.map { gear -> val adjacentParts = schematic.parts.filter { it.adjacentPositions.contains(gear.pos) } if (adjacentParts.size > 1) { adjacentParts.fold(1) {acc, part -> acc * part.number} } else { 0 } } return gearRatios.sum() } private fun findAdjacentToSymbols(schematic: Schematic): List<Part> { val symbolPositions = schematic.symbols.map { it.pos } return schematic.parts.filter { part -> part.adjacentPositions.any { symbolPositions.contains(it) } } } private fun parseSchematic(input: String): Schematic { val lines = input.trim().lines() val folded = lines.fold(Schematic() to 0) { acc, line -> val numberMatches = numbersRegex.findAll(line) val parts = numberMatches.map { m -> Part(m.value.toInt(), Pos(m.range.first, acc.second), Pos(m.range.last, acc.second)) } val symbols = symbolRegex.findAll(line).map { m -> Symbol(m.value.first(), Pos(m.range.first, acc.second)) } val updatedSchematic = Schematic(acc.first.parts + parts, acc.first.symbols + symbols) updatedSchematic to acc.second + 1 } return folded.first } }
0
Kotlin
0
0
0cd9676a7d1fec01858ede1ab0adf254d17380b0
2,474
advent-of-code-23
Apache License 2.0
lib/src/main/kotlin/com/bloidonia/advent/day03/Day03.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day03 import com.bloidonia.advent.readList data class Diagnostic(val bits: List<Boolean>) { fun isOn(bit: Int) = bits[bit] fun isOn(bit: Int, required: Boolean) = bits[bit] == required fun toInt() = bits.toInt() override fun toString(): String { return bits.fold("") { acc, boo -> acc + (if (boo) "1" else "0") } + " (" + toInt() + ")" } } fun List<Boolean>.toInt() = this.foldIndexed(0) { idx, acc, current -> if (current) acc.or(1.shl(this.size - 1 - idx)) else acc } private fun List<Diagnostic>.mostCommonAtOffset(offset: Int) = this.count { it.isOn(offset) } > this.size / 2.0 private fun bitwiseInverse(number: Int, bitWidth: Int) = 1.shl(bitWidth).minus(1).xor(number) fun String.toDiagnostic() = Diagnostic(this.fold(listOf()) { list, ch -> list + (ch == '1') }) fun List<Diagnostic>.findOne(fn: (Int, Double) -> Boolean): Diagnostic = findOne(this, 0, fn) tailrec fun findOne(current: List<Diagnostic>, index: Int, fn: (Int, Double) -> Boolean): Diagnostic { return if (current.size < 2) { current.first() } else { findOne( current.filter { it.isOn(index, fn.invoke(current.count { it.isOn(index) }, current.size / 2.0)) }, index + 1, fn ) } } fun List<Diagnostic>.gammaTimesEpsilon(): Int = this[0].bits.size.let { bitWidth -> (0 until bitWidth).map(this::mostCommonAtOffset).toInt().let { it * bitwiseInverse(it, bitWidth) } } fun List<Diagnostic>.part2() = this.findOne { a, b -> a >= b }.toInt() * this.findOne { a, b -> a < b }.toInt() fun main() { println(readList("/day03input.txt") { it.toDiagnostic() }.gammaTimesEpsilon()) println(readList("/day03input.txt") { it.toDiagnostic() }.part2()) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
1,767
advent-of-kotlin-2021
MIT License
src/Day05.kt
Fenfax
573,898,130
false
{"Kotlin": 30582}
fun main() { fun part1(input: Map<Int, MutableList<Char>>, commands: List<List<Int>>): String { commands.forEach { number -> input[number[1]]?.let { input[number[2]]?.addAll((1..number[0]).map { _ -> it.removeLast() }) } } return input.map { it.value.last() }.joinToString("") } fun part2(input: Map<Int, MutableList<Char>>, commands: List<List<Int>>): String { commands.forEach { number -> input[number[1]]?.let { input[number[2]]?.addAll((1..number[0]).map { _ -> it.removeLast() }.reversed()) } } return input.map { it.value.last() }.joinToString("") } fun generateStorage(input: List<String>): Map<Int, MutableList<Char>> { val positions = input.last().toList().asSequence().mapIndexedNotNull { index, c -> index.takeIf { c.isDigit() } }.toList() return positions.mapIndexed { index, pos -> index + 1 to input.filterIndexed { ind, _ -> ind != input.size - 1 }.reversed().mapNotNull { it[pos].takeIf { char -> char.isLetter() } } .toMutableList() }.toMap() } val input = readInput("Day05") val splitInput = input.splitWhen { it == "" } val commands = splitInput[1].map { it.split(" ").filter { s -> s.all { c -> c.isDigit() } }.map { s -> s.toInt() } } println(part1(generateStorage(splitInput[0]), commands)) println(part2(generateStorage(splitInput[0]), commands)) }
0
Kotlin
0
0
28af8fc212c802c35264021ff25005c704c45699
1,502
AdventOfCode2022
Apache License 2.0
src/Day16.kt
frango9000
573,098,370
false
{"Kotlin": 73317}
import kotlin.math.max fun main() { val input = readInput("Day16") printTime { print(Day16.part1(input)) } printTime { print(Day16.part2(input)) } } class Day16 { companion object { fun part1(input: List<String>): Int { val valves = input.map { it.split( "Valve ", " has flow rate=", "; tunnel leads to valve ", "; tunnels lead to valves " ).drop(1) }.map { Valve(it[0], it[1].toInt(), it[2].split(", ").toSet()) } for (valve in valves) { valve.tunnels.addAll(valve.tunnelsTo.map { to -> valves.find { it.name == to }!! }) } val valvesMap: Map<Valve, Map<Valve, Int>> = valves.filter { origin -> origin.rate > 0 || origin.name == "AA" }.associateWith { origin -> valves.filter { it !== origin && it.rate > 0 }.associateWith { target -> bfs(origin, target) } } val valvesIndexes: Map<Valve, Int> = valvesMap.keys.withIndex().associateWith { it.index }.mapKeys { it.key.value } return dfs(valves.find { it.name == "AA" }!!, valvesMap, valvesIndexes) } private fun bfs(from: Valve, target: Valve): Int { val queue = ArrayDeque<Pair<Valve, Int>>() queue.add(from to 0) val visited = mutableSetOf<Valve>() while (queue.isNotEmpty()) { val next = queue.removeFirst() if (visited.contains(next.first)) continue visited.add(next.first) if (target == next.first) { return next.second } queue.addAll(next.first.tunnels.map { it to next.second + 1 }) } error("No Path Found") } private fun dfs( start: Valve, valvesMap: Map<Valve, Map<Valve, Int>>, valvesIndexes: Map<Valve, Int>, timeLeft: Int = 30, valvesState: Int = 0 ): Int { var maxPressure = 0 for ((neighbor, distance) in valvesMap[start]!!.entries) { val bit = 1 shl valvesIndexes[neighbor]!! if (valvesState and bit > 0) continue val newTimeLeft = timeLeft - distance - 1 if (newTimeLeft <= 0)//try 1 continue maxPressure = max( maxPressure, dfs( neighbor, valvesMap, valvesIndexes, newTimeLeft, valvesState or bit ) + neighbor.rate * newTimeLeft ) } return maxPressure } private fun dfs_v1(path: List<Valve>, valvesMap: Map<Valve, Map<Valve, Int>>, timeLeft: Int = 30): Int { if (timeLeft <= 1) { return 0 } val current = path.last() val timeInCurrentCave = if (current.rate > 0) 1 else 0 val valveTotalPressure = current.rate * (timeLeft - timeInCurrentCave) val openValves = valvesMap[current]!!.filter { !path.contains(it.key) } if (openValves.isEmpty()) { return valveTotalPressure } return valveTotalPressure + (openValves.maxOfOrNull { (target, distance) -> dfs_v1(listOf(*path.toTypedArray(), target), valvesMap, timeLeft - (timeInCurrentCave + distance)) } ?: 0) } fun part2(input: List<String>): Int { val valves = input.map { it.split( "Valve ", " has flow rate=", "; tunnel leads to valve ", "; tunnels lead to valves " ).drop(1) }.map { Valve(it[0], it[1].toInt(), it[2].split(", ").toSet()) } for (valve in valves) { valve.tunnels.addAll(valve.tunnelsTo.map { to -> valves.find { it.name == to }!! }) } val valvesMap: Map<Valve, Map<Valve, Int>> = valves.filter { origin -> origin.rate > 0 || origin.name == "AA" }.associateWith { origin -> valves.filter { it !== origin && it.rate > 0 }.associateWith { target -> bfs(origin, target) } } val valvesIndexes: Map<Valve, Int> = valvesMap.keys.withIndex().associateWith { it.index }.mapKeys { it.key.value } val start = valves.find { it.name == "AA" }!! val mask = (1 shl valvesIndexes.size) - 1 var max = 0 for (i in 0..(mask / 2)) { max = max( max, dfs(start, valvesMap, valvesIndexes, 26, i) + dfs(start, valvesMap, valvesIndexes, 26, mask xor i) ) } return max } } class Valve(val name: String, val rate: Int, val tunnelsTo: Set<String>) { val tunnels: MutableSet<Valve> = mutableSetOf() override fun toString(): String { return "Valve(name='$name', rate=$rate)" } override fun equals(other: Any?): Boolean { return name == (other as Valve).name } override fun hashCode(): Int { return name.hashCode() } } }
0
Kotlin
0
0
62e91dd429554853564484d93575b607a2d137a3
5,406
advent-of-code-22
Apache License 2.0
src/aoc2022/Day12.kt
nguyen-anthony
572,781,123
false
null
package aoc2022 import utils.readInputAsList data class Step(val point: Pair<Int,Int>, val distance: Int, val parent: Step?) fun main() { fun letter(ch: Char): Char { return when (ch) { 'S' -> 'a' 'E' -> 'z' else -> ch } } fun findShortest(start: Pair<Int,Int>, map: List<List<Char>>): Int { val queue = ArrayDeque<Step>() val visited = mutableSetOf(start) queue.addFirst(Step(start, 0, null)) while (queue.isNotEmpty()) { val node = queue.removeFirst() if (map[node.point.first][node.point.second] == 'E') { return node.distance } setOf( if (node.point.second < map[node.point.first].size - 1) node.point.first to node.point.second + 1 else null, if (node.point.second > 0) node.point.first to node.point.second - 1 else null, if (node.point.first > 0) node.point.first - 1 to node.point.second else null, if (node.point.first < map.size - 1) node.point.first + 1 to node.point.second else null) .filterNotNull() .filter {letter(map[it.first][it.second]) - letter(map[node.point.first][node.point.second]) <= 1 } .filter { !visited.contains(it) } .forEach { visited.add(it) queue.add(Step(it, node.distance + 1, node)) } } return Int.MAX_VALUE } fun part1(input: List<String>): Int { val map = input.map{ it.toList() } lateinit var starts : Pair<Int,Int> for(i in map.indices) { for (j in 0 until map[i].size) { if (map[i][j] == 'S') { starts = i to j } } } return findShortest(starts, map) } fun part2(input: List<String>): Int { val map = input.map{ it.toList() } var starts = mutableListOf<Pair<Int,Int>>() for(i in map.indices) { for (j in 0 until map[i].size) { if (map[i][j] == 'S' || map[i][j] == 'a') { starts.add(i to j) } } } return starts.minOf { findShortest(it, map) } } val input = readInputAsList("Day12", "2022") println(part1(input)) println(part2(input)) // val testInput = readInputAsList("Day12_test", "2022") // check(part1(testInput) == 0) // check(part2(testInput) == 0) }
0
Kotlin
0
0
9336088f904e92d801d95abeb53396a2ff01166f
2,538
AOC-2022-Kotlin
Apache License 2.0
src/year2023/day05/Day05.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day05 import check import readInput import kotlin.math.max import kotlin.math.min fun main() { val testInput = readInput("2023", "Day05_test") check(part1(testInput), 35) check(part2(testInput), 46) val input = readInput("2023", "Day05") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val seeds = input.first().substringAfter("seeds: ").split(" ").map { it.toLong() } val locationBySeed = seeds.associateWith { it }.toMutableMap() val seedRangeMappings = input.toSeedRangeMappings() for (seed in seeds) { for (seedRangeMapping in seedRangeMappings) { val location = locationBySeed.getValue(seed) locationBySeed[seed] = updateSeedLocation(seedRangeMapping, location) } } return locationBySeed.values.min().toInt() } private fun updateSeedLocation(seedRangeMappings: List<SeedRangeMapping>, location: Long): Long { var updatedLocation = location for (seedRangeMapping in seedRangeMappings) { if (updatedLocation in seedRangeMapping.source) { updatedLocation = seedRangeMapping.mapSeed(updatedLocation) break } } return updatedLocation } private fun part2(input: List<String>): Int { val seedRangeMappings = input.toSeedRangeMappings() var currentSeedRanges = input.toSeedRanges() for (seedRangeMapping in seedRangeMappings) { currentSeedRanges = currentSeedRanges.flatMap { updateSeedRange(it, seedRangeMapping) }.toSet() } return currentSeedRanges.minOf { it.first }.toInt() } private fun updateSeedRange( seedRange: LongRange, seedRangeMappings: List<SeedRangeMapping>, ) = buildSet { var remainingSeedRange = seedRange for (seedRangeMapping in seedRangeMappings.sortedBy { it.source.first }) { if (remainingSeedRange.last < seedRangeMapping.source.first || remainingSeedRange.first > seedRangeMapping.source.last) { continue } if (remainingSeedRange.first < seedRangeMapping.source.first) { add(remainingSeedRange.first..<seedRangeMapping.source.first) } val lowerBound = max(seedRangeMapping.source.first, remainingSeedRange.first) val upperBound = min(seedRangeMapping.source.last, remainingSeedRange.last) add(seedRangeMapping.mapSeed(lowerBound)..seedRangeMapping.mapSeed(upperBound)) if (remainingSeedRange.last > seedRangeMapping.source.last) { remainingSeedRange = seedRangeMapping.source.last + 1..remainingSeedRange.last } else { remainingSeedRange = LongRange.EMPTY break } } if (remainingSeedRange != LongRange.EMPTY) { add(remainingSeedRange) } } private fun List<String>.toSeedRangeMappings(): List<List<SeedRangeMapping>> = drop(2).fold(mutableListOf<MutableList<SeedRangeMapping>>()) { acc, l -> if (acc.isEmpty() || l.isBlank()) { acc += mutableListOf<SeedRangeMapping>() } if (l.isNotBlank() && l.first().isDigit()) { val (destStart, sourceStart, length) = l.split(" ").map { it.toLong() } acc.last() += SeedRangeMapping( sourceStart until (sourceStart + length), destStart until (destStart + length) ) } acc } private fun List<String>.toSeedRanges() = first() .substringAfter("seeds: ") .split(" ") .map { it.toLong() } .chunked(2) .map { val start = it.first() val length = it.last() start until (start + length) } .toSet() private fun SeedRangeMapping.mapSeed(seedLocation: Long): Long { return if (seedLocation in source) { val offset = seedLocation - source.first destination.first + offset } else seedLocation } private data class SeedRangeMapping( val source: LongRange, val destination: LongRange, )
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
3,959
AdventOfCode
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2023/Day07.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2023 import se.saidaspen.aoc.util.* import java.lang.RuntimeException fun main() = Day07.run() object Day07 : Day(2023, 7) { private const val RANKS = "A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, 2, *" override fun part1() = input.lines() .sortedWith(handComparator).reversed() .mapIndexed { i, e -> (i + 1) * e.split(" ")[1].toLong() } .sum() override fun part2() = input.lines() .map { it.replace("J", "*") } // J is actually Joker! .sortedWith(handComparator).reversed() .mapIndexed { i, e -> (i + 1) * e.split(" ")[1].toLong() } .sum() private val handComparator = Comparator<String> { a, b -> val typeA = handType(a.split(" ")[0]) val typeB = handType(b.split(" ")[0]) when { typeA > typeB -> -1 typeB > typeA -> 1 else -> a.e().zip(b.e()).filter { it.first != it.second }.map { if (RANKS.indexOf(it.first) < RANKS.indexOf(it.second)) -1 else 1 }.first() } } private fun handType(a: String): Int { val occurences = a.replace("*", "").e().histo().values val jokers = a.e().count { it == '*' } return when { jokers == 5 -> 7 jokers + occurences.max() == 5 -> 7 // Five of a kind jokers + occurences.max() == 4 -> 6 // Four of a kind occurences.max() == 3 && occurences.filter { it == 2 }.size == 1 -> 5 // Full house occurences.max() == 2 && jokers + occurences.filter { it == 2 }.size == 3 -> 5 // Full house jokers + occurences.max() == 3 -> 4 // Three of a kind jokers + occurences.max() == 2 && occurences.size == 3 -> 3 // Two pairs jokers + occurences.max() == 2 -> 2 // One pair occurences.size == 5 -> 1 // High card else -> throw RuntimeException("Unknown type") } } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,944
adventofkotlin
MIT License
src/main/Day16.kt
ssiegler
572,678,606
false
{"Kotlin": 76434}
package day16 import utils.readInput import java.util.* import kotlin.math.max data class Valves( private val flows: Map<String, Int>, private val tunnels: Map<String, List<String>> ) { private val flowValves = flows.entries.filter { (_, flow) -> flow > 0 }.map { (valve, _) -> valve } private val distances: Map<Pair<String, String>, Int> by lazy { val distances = mutableMapOf<Pair<String, String>, Int>() for (u in tunnels.keys) { distances[u to u] = 0 for (v in tunnels[u] ?: emptyList()) { distances[u to v] = 1 } } for (k in tunnels.keys) { for (i in tunnels.keys) { for (j in tunnels.keys) { val whole = distances[i to j] val first = distances[i to k] val second = distances[k to j] if ( first != null && second != null && (whole == null || whole > first + second) ) { distances[i to j] = first + second } } } } return@lazy distances.filterKeys { (_, dest) -> dest in flowValves } } data class State( val remaining: Int, val position: String, val openValves: List<String>, val rate: Int, val total: Int ) { fun flow(): Int = total + remaining * rate } fun maximalPressure( pathValues: MutableMap<Set<String>, Int> = mutableMapOf(), minutes: Int = 30 ): Int { var maxFlow = 0 val queue = ArrayDeque<State>() queue.push(State(minutes, "AA", emptyList(), 0, 0)) while (queue.isNotEmpty()) { val state = queue.pop() maxFlow = max(maxFlow, state.flow()) pathValues[state.openValves.toSet()] = max(state.flow(), pathValues[state.openValves.toSet()] ?: 0) if (state.remaining >= 0) { val rate = flows[state.position]!! if (state.position !in state.openValves && rate > 0) { queue.push( State( state.remaining - 1, state.position, state.openValves + state.position, state.rate + rate, state.total + state.rate ) ) } else { for (destination in flowValves - state.openValves.toSet()) { val distance = distances[state.position to destination]!! val remaining = state.remaining - distance if (remaining > 1) { queue.push( State( remaining, destination, state.openValves, state.rate, state.total + (state.rate * distance) ) ) } } } } } return maxFlow } } fun List<String>.readValves(): Valves { val flows = mutableMapOf<String, Int>() val tunnels = mutableMapOf<String, List<String>>() forEach { line -> val valves = "[A-Z][A-Z]".toRegex().findAll(line).map { it.value }.toList() flows[valves[0]] = """\d+""".toRegex().find(line)!!.value.toInt() tunnels[valves[0]] = valves.subList(1, valves.size) } return Valves(flows, tunnels) } fun part1(filename: String) = readInput(filename).readValves().maximalPressure(minutes = 30) fun part2(filename: String): Int { val pathValues = mutableMapOf<Set<String>, Int>() readInput(filename).readValves().maximalPressure(pathValues, 26) return pathValues .asSequence() .flatMap { (path, flow) -> pathValues .asSequence() .drop(1) .filter { it.key.toSet().intersect(path.toSet()).isEmpty() } .map { flow + it.value } } .max() } private const val filename = "Day16" fun main() { println(part1(filename)) println(part2(filename)) }
0
Kotlin
0
0
9133485ca742ec16ee4c7f7f2a78410e66f51d80
4,436
aoc-2022
Apache License 2.0
src/year2023/day06/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2023.day06 import arrow.core.nonEmptyListOf import utils.ProblemPart import utils.product import utils.readInputs import utils.runAlgorithm fun main() { val (realInput, testInputs) = readInputs(2023, 6) runAlgorithm( realInput = realInput, testInputs = testInputs, part1 = ProblemPart( expectedResultsForTests = nonEmptyListOf(288), algorithm = ::part1, ), part2 = ProblemPart( expectedResultsForTests = nonEmptyListOf(71503), algorithm = ::part2, ), ) } private fun part1(input: List<String>): Long { return parseMultipleRaces(input) .asSequence() .map { (time, highScore) -> val wins = (time / 2 downTo 1).asSequence() .map { timeHeld -> (time - timeHeld) * timeHeld } .takeWhile { it > highScore } .count() * 2 if (time % 2L == 0L) wins - 1 else wins } .product() } private fun parseMultipleRaces(input: List<String>): List<Pair<Long, Long>> { val (time, distance) = input return time.toIntSequence() .zip(distance.toIntSequence()) .toList() } private fun String.toIntSequence() = splitToSequence(" +".toRegex()).drop(1).map { it.toLong() } private fun part2(input: List<String>): Int { val (time, highScore) = parseSingleRace(input) val wins = (time / 2 downTo 1).asSequence() .map { timeHeld -> (time - timeHeld) * timeHeld } .takeWhile { it > highScore } .count() * 2 return if (time % 2L == 0L) wins - 1 else wins } private fun parseSingleRace(input: List<String>) = Pair( trimInput(input[0]).toLong(), trimInput(input[1]).toLong(), ) private fun trimInput(input: String) = input.drop(9).replace(" +".toRegex(), "")
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
1,828
Advent-of-Code
Apache License 2.0
src/year_2021/day_02/Day02.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2021.day_02 import readInput enum class Heading(val text: String) { FORWARD("forward"), DOWN("down"), UP("up"), ; companion object { fun fromText(text: String): Heading { return Heading.values().first { it.text == text } } } } data class Direction( val heading: Heading, val amount: Int ) data class AimlessPosition( var horizontal: Int, var depth: Int ) { fun apply(direction: Direction) { when (direction.heading) { Heading.FORWARD -> horizontal += direction.amount Heading.UP -> depth -= direction.amount Heading.DOWN -> depth += direction.amount } } } data class AimPosition( var horizontal: Int, var depth: Int, var aim: Int ) { fun apply(direction: Direction) { when (direction.heading) { Heading.FORWARD -> { horizontal += direction.amount depth += (direction.amount * aim) } Heading.UP -> aim -= direction.amount Heading.DOWN -> aim += direction.amount } } } object Day02 { /** * Modify position by following the directions exactly * * @return the resulting horizontal * depth position */ fun solutionOne(directionsText: List<String>): Int { val position = AimlessPosition(0, 0) val course = parseCourse(directionsText) course.forEach { direction -> position.apply(direction) } return position.horizontal * position.depth } /** * Instead of modifying depth directly, change the "aim" then move * the depth when moving forward by aim * forward * * @return the resulting horizontal * depth position */ fun solutionTwo(directionsText: List<String>): Int { val position = AimPosition(0, 0, 0) val course = parseCourse(directionsText) course.forEach { direction -> position.apply(direction) } return position.horizontal * position.depth } private fun parseCourse(directionsText: List<String>): List<Direction> { return directionsText.map { direction -> val split = direction.split(" ") Direction( heading = Heading.fromText(split[0]), amount = split[1].toInt() ) } } } fun main() { val sonarDepthsText = readInput("year_2021/day_02/Day02.txt") val solutionOne = Day02.solutionOne(sonarDepthsText) println("Solution 1: $solutionOne") val solutionTwo = Day02.solutionTwo(sonarDepthsText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
2,644
advent_of_code
Apache License 2.0
src/Day15.kt
makohn
571,699,522
false
{"Kotlin": 35992}
import kotlin.math.abs fun main() { val day = "15" fun List<List<Vec2>>.scanArea(row: Int) = this.map { (scanner, beacon) -> val yDistance = abs(scanner.y - row) val distance = manhattanDistance(scanner, beacon) if (yDistance <= distance) { (scanner.x - distance) + yDistance..(scanner.x + distance) - yDistance } else IntRange.EMPTY } fun parseInput(input: List<String>) = input .map { it.findInts() } .flatMap { (x1, y1, x2, y2) -> listOf( Vec2(x1, y1), Vec2(x2, y2)) } .chunked(2) fun List<IntRange>.merge() = this .filter { !it.isEmpty() } .sortedBy { it.first } .foldIndexed(ArrayDeque<IntRange>()) { idx, stack, range -> if (idx == 0) stack.add(range) else if (range.last <= stack.last().last) return@foldIndexed stack else if (range.first > stack.last().last + 1) stack.add(range) else stack.add(stack.removeLast().first..range.last) stack } fun List<IntRange>.notIncludes(otherRange: IntRange): IntRange? = this.firstOrNull { otherRange.first < it.first || otherRange.last > it.last } fun part1(input: List<String>, row: Int): Int { val report = parseInput(input) val ans = report.scanArea(row).merge() return ans.sumOf { it.last - it.first } } fun part2(input: List<String>, range: IntRange): Long { val report = parseInput(input) for (row in range) { val ans = report.scanArea(row).merge().notIncludes(range) if (ans != null) { val col = (range.toSet() - ans.toSet()).first() return col * 4000000L + row } } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput, 10).also { println(it) } == 26) check(part2(testInput, 0..20).also { println(it) } == 56000011L) val input = readInput("Day${day}") println(part1(input, 2000000)) println(part2(input, 0..4000000)) }
0
Kotlin
0
0
2734d9ea429b0099b32c8a4ce3343599b522b321
2,139
aoc-2022
Apache License 2.0
src/main/kotlin/g2601_2700/s2662_minimum_cost_of_a_path_with_special_roads/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2601_2700.s2662_minimum_cost_of_a_path_with_special_roads // #Medium #Array #Heap_Priority_Queue #Graph #Shortest_Path // #2023_07_25_Time_690_ms_(100.00%)_Space_59.5_MB_(50.00%) import java.util.PriorityQueue class Solution { fun minimumCost(start: IntArray, target: IntArray, specialRoads: Array<IntArray>): Int { val pointList = mutableListOf<Point>() val costMap = HashMap<Pair<Point, Point>, Int>() val distMap = HashMap<Point, Int>() val sp = Point(start[0], start[1]) distMap[sp] = 0 for (road in specialRoads) { val p = Point(road[0], road[1]) val q = Point(road[2], road[3]) val cost = road[4] if (costMap.getOrDefault(Pair(p, q), Int.MAX_VALUE) > cost) { costMap[Pair(p, q)] = cost } pointList.add(p) pointList.add(q) distMap[p] = Int.MAX_VALUE distMap[q] = Int.MAX_VALUE } val tp = Point(target[0], target[1]) pointList.add(tp) distMap[tp] = Int.MAX_VALUE val points = pointList.distinct() val pq = PriorityQueue<PointWithCost>() pq.offer(PointWithCost(sp, 0)) while (pq.isNotEmpty()) { val curr = pq.poll() val cost = curr.cost val cp = curr.p if (cp == tp) return cost for (np in points) { if (cp == np) continue var nextCost = cost + dist(cp, np) if (costMap.containsKey(Pair(cp, np))) { nextCost = nextCost.coerceAtMost(cost + costMap[Pair(cp, np)]!!) } if (nextCost < distMap[np]!!) { distMap[np] = nextCost pq.offer(PointWithCost(np, nextCost)) } } } return -1 } fun dist(sp: Point, tp: Point): Int { return kotlin.math.abs(sp.x - tp.x) + kotlin.math.abs(sp.y - tp.y) } } data class Point(val x: Int, val y: Int) data class PointWithCost(val p: Point, val cost: Int) : Comparable<PointWithCost> { override fun compareTo(other: PointWithCost) = compareValuesBy(this, other) { it.cost } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,227
LeetCode-in-Kotlin
MIT License
src/Day03.kt
thorny-thorny
573,065,588
false
{"Kotlin": 57129}
class PriorityFlags { companion object { private fun itemPriority(item: Char) = when (item) { in 'a'..'z' -> item - 'a' + 1 in 'A'..'Z' -> item - 'A' + 27 else -> throw Exception("Unknown item") } fun allRaised() = PriorityFlags().apply { value = ULong.MAX_VALUE } } private var value: ULong = 0UL fun priorityIfSet(item: Char): Int? { val priority = itemPriority(item) return when (value and (1UL shl (priority - 1))) { 0UL -> null else -> priority } } fun set(item: Char) { value = value or (1UL shl (itemPriority(item) - 1)) } operator fun times(other: PriorityFlags): PriorityFlags { return PriorityFlags().apply { value = value and other.value } } operator fun timesAssign(other: PriorityFlags) { value = value and other.value } } fun main() { fun part1(input: List<String>): Int { return input.sumOf { sack -> val compartmentSize = sack.length / 2 val firstCompartmentFlags = PriorityFlags().apply { (0 until compartmentSize).forEach { set(sack[it]) } } (compartmentSize until sack.length).firstNotNullOf { firstCompartmentFlags.priorityIfSet(sack[it]) } } } fun part2(input: List<String>): Int { return input .asSequence() .chunked(3) .map { sacks -> val flags = PriorityFlags.allRaised() (0 until sacks.lastIndex).forEach { index -> flags *= PriorityFlags().apply { sacks[index].forEach { set(it) } } } sacks.last().firstNotNullOf { flags.priorityIfSet(it) } } .sum() } 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
843869d19d5457dc972c98a9a4d48b690fa094a6
2,108
aoc-2022
Apache License 2.0
src/main/kotlin/Day12.kt
gijs-pennings
573,023,936
false
{"Kotlin": 20319}
fun main() { val lines = readInput(12) val w = lines[0].length val h = lines.size val grid = Array(w) { x -> Array(h) { y -> Node(x, y, lines[y][x]) } } val nodes = grid.flatten() for (n in nodes) { if (n.x-1 >= 0 && n.h <= grid[n.x-1][n.y].h + 1) n.adjRev.add(grid[n.x-1][n.y]) if (n.x+1 < w && n.h <= grid[n.x+1][n.y].h + 1) n.adjRev.add(grid[n.x+1][n.y]) if (n.y-1 >= 0 && n.h <= grid[n.x][n.y-1].h + 1) n.adjRev.add(grid[n.x][n.y-1]) if (n.y+1 < h && n.h <= grid[n.x][n.y+1].h + 1) n.adjRev.add(grid[n.x][n.y+1]) } val first = nodes.first { it.isEnd } first.dist = 0 val queue = ArrayDeque<Node>() queue.add(first) while (queue.isNotEmpty()) { val n = queue.removeFirst() for (m in n.adjRev.filter { !it.visited }) { m.dist = n.dist + 1 queue.addLast(m) } } println(nodes.filter { it.isStart }.minOf { it.dist }) } private data class Node(val x: Int, val y: Int, val c: Char) { val h = when (c) { 'S' -> 0 'E' -> 25 else -> c - 'a' } val isStart = h == 0 // use `c == 'S'` for part 1 val isEnd = c == 'E' val adjRev = mutableListOf<Node>() var dist = INF val visited get() = dist < INF }
0
Kotlin
0
0
8ffbcae744b62e36150af7ea9115e351f10e71c1
1,287
aoc-2022
ISC License
src/day21/Day21.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day21 import readInput import readTestInput private sealed interface MonkeyTask { class SolvedTask(val solution: Long) : MonkeyTask class OpenTask( val lhs: String, val rhs: String, val operation: Char ) : MonkeyTask { fun solve(lhsValue: Long, rhsValue: Long): SolvedTask = SolvedTask( solution = when (operation) { '+' -> lhsValue + rhsValue '-' -> lhsValue - rhsValue '*' -> lhsValue * rhsValue '/' -> lhsValue / rhsValue else -> error("""Unsupported operation "$operation"!""") } ) } } private fun MonkeyTask.solutionOrNull(): Long? = when (this) { is MonkeyTask.OpenTask -> null is MonkeyTask.SolvedTask -> solution } private fun List<String>.toMonkeyTasks(): Map<String, MonkeyTask> = associate { line -> val (name, task) = line.split(": ") val monkeyTask = task.toMonkeyTask() name to monkeyTask } private fun Map<String, MonkeyTask>.solveTask(monkeyName: String): MonkeyTask.SolvedTask { val solvedTasks = this.solveAllSolvableTasks() return solvedTasks.getValue(monkeyName) as MonkeyTask.SolvedTask } private val Map<String, MonkeyTask>.solvedTasks: Int get() = count { (_, monkeyTask) -> monkeyTask is MonkeyTask.SolvedTask } private val monkeyTaskRegex = """(\w+) ([*/+-]) (\w+)""".toRegex() private fun String.toMonkeyTask(): MonkeyTask { val regexMatch = monkeyTaskRegex.matchEntire(this) return if (regexMatch == null) { MonkeyTask.SolvedTask(this.toLong()) } else { val (lhs, operation, rhs) = regexMatch.destructured MonkeyTask.OpenTask( lhs = lhs, rhs = rhs, operation = operation.single() ) } } private fun Map<String, MonkeyTask>.solveAllSolvableTasks(): Map<String, MonkeyTask> { var ongoingMonkeyTasks = this var previouslySolvedTasks = 0 var solvedTasks = this.solvedTasks while (solvedTasks > previouslySolvedTasks) { ongoingMonkeyTasks = ongoingMonkeyTasks.mapValues { (_, monkeyTask) -> if (monkeyTask is MonkeyTask.OpenTask) { val lhs = ongoingMonkeyTasks[monkeyTask.lhs]?.solutionOrNull() val rhs = ongoingMonkeyTasks[monkeyTask.rhs]?.solutionOrNull() if (lhs != null && rhs != null) { return@mapValues monkeyTask.solve(lhs, rhs) } } return@mapValues monkeyTask } previouslySolvedTasks = solvedTasks solvedTasks = ongoingMonkeyTasks.solvedTasks } return ongoingMonkeyTasks } private fun Map<String, MonkeyTask>.reverseSolve( implicitlyKnownMonkeyTask: String, equationValue: Long, ): Map<String, MonkeyTask> { val monkeyTasks = this val solutionsToApply = mutableListOf( implicitlyKnownMonkeyTask to equationValue ) val knownSolutions = mutableMapOf<String, Long>() while (solutionsToApply.isNotEmpty()) { val (knownMonkeyName, knownSolution) = solutionsToApply.removeFirst() for ((monkeyName, monkeyTask) in monkeyTasks) { if (monkeyName == knownMonkeyName && monkeyTask is MonkeyTask.OpenTask) { val lhsValue = monkeyTasks[monkeyTask.lhs]?.solutionOrNull() ?: knownSolutions[monkeyTask.lhs] val rhsValue = monkeyTasks[monkeyTask.rhs]?.solutionOrNull() ?: knownSolutions[monkeyTask.rhs] if (lhsValue == null) { val solved = when (monkeyTask.operation) { '+' -> knownSolution - checkNotNull(rhsValue) '-' -> knownSolution + checkNotNull(rhsValue) '*' -> knownSolution / checkNotNull(rhsValue) '/' -> knownSolution * checkNotNull(rhsValue) else -> error("oopsie!") } solutionsToApply += (monkeyTask.lhs to solved) } if (rhsValue == null) { val solved = when (monkeyTask.operation) { '+' -> knownSolution - checkNotNull(lhsValue) '-' -> -1 * (knownSolution - checkNotNull(lhsValue)) '*' -> knownSolution / checkNotNull(lhsValue) '/' -> checkNotNull(lhsValue) / knownSolution else -> error("oopsie!") } solutionsToApply += (monkeyTask.rhs to solved) } } } knownSolutions[knownMonkeyName] = knownSolution } return monkeyTasks + knownSolutions .mapValues { (monkeyName, solution) -> MonkeyTask.SolvedTask(solution) } } private fun part1(input: List<String>): Long { val monkeyTasks = input.toMonkeyTasks() val solvedRootTask = monkeyTasks.solveTask("root") return solvedRootTask.solution } private fun part2(input: List<String>): Long { val monkeyTasks = input.toMonkeyTasks() val rootTask = monkeyTasks.getValue("root") as MonkeyTask.OpenTask val rootLhs = rootTask.lhs val rootRhs = rootTask.rhs val relevantTasks = monkeyTasks .filterNot { (monkeyName, _) -> monkeyName == "humn" } val solvedRelevantTasks = relevantTasks.solveAllSolvableTasks() val rootLhsTask = solvedRelevantTasks.getValue(rootLhs) val rootRhsTask = solvedRelevantTasks.getValue(rootRhs) val (implicitlyKnownMonkeyTask, equationValue) = when { rootLhsTask is MonkeyTask.SolvedTask -> rootRhs to rootLhsTask.solution rootRhsTask is MonkeyTask.SolvedTask -> rootLhs to rootRhsTask.solution else -> error("Cannot solve with equation, when neither lhs nor rhs are known!") } val solvedTasks = solvedRelevantTasks.reverseSolve(implicitlyKnownMonkeyTask, equationValue) return checkNotNull(solvedTasks.getValue("humn").solutionOrNull()) } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day21") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
6,294
advent-of-code-kotlin-2022
Apache License 2.0
src/day02/Day02.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day02 import readInput private const val DAY_ID = "02" private enum class Shape(val score: Int) { // rock A(1) { override fun wins(): Shape = C override fun loses(): Shape = B }, // paper B(2) { override fun wins(): Shape = A override fun loses(): Shape = C }, // scissors C(3) { override fun wins(): Shape = B override fun loses(): Shape = A }; abstract fun wins(): Shape abstract fun loses(): Shape fun wins(opponent: Shape): Boolean = wins() == opponent } private enum class RoundEnd(val score: Int) { // you need to lose X(0), // you need to end the round in a draw Y(3), // you need to win Z(6) } fun main() { fun part1(input: List<String>): Int { fun playRound(me: Shape, opponent: Shape): Int = when { me == opponent -> 3 me.wins(opponent) -> 6 else -> 0 } val shape = mapOf("X" to "A", "Y" to "B", "Z" to "C") return input.map { it.split(" ") } .sumOf { (s1, s2) -> val opponent = enumValueOf<Shape>(s1) val me = enumValueOf<Shape>(shape[s2]!!) me.score + playRound(me, opponent) } } fun part2(input: List<String>): Int { fun myResponse(opponent: Shape, roundEnd: RoundEnd): Shape = when (roundEnd) { // need to lose RoundEnd.X -> opponent.wins() // need to win RoundEnd.Z -> opponent.loses() // need to end the round in a draw else -> opponent } return input.map { it.split(" ") } .sumOf { (s1, s2) -> val opponent = enumValueOf<Shape>(s1) val roundEnd = enumValueOf<RoundEnd>(s2) myResponse(opponent, roundEnd).score + roundEnd.score } } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day${DAY_ID}/Day$DAY_ID") println(part1(input)) // answer = 14375 println(part2(input)) // answer = 10274 }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
2,264
aoc-2022-in-kotlin
Apache License 2.0