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/Day07.kt
Vampire
572,990,104
false
{"Kotlin": 57326}
fun main() { data class File( val name: String, val size: Int ) data class Dir( val name: String, val parent: Dir? = null, val dirs: MutableList<Dir> = mutableListOf(), val files: MutableList<File> = mutableListOf() ) { val size: Int get() = dirs.sumOf(Dir::size) + files.sumOf(File::size) val descendentDirs: List<Dir> get() = dirs.flatMap { it.allDirs } val allDirs: List<Dir> get() = descendentDirs + this } fun buildDirTree(cliOutput: List<String>): Dir { val root = Dir("/") var cur: Dir? = null cliOutput.forEach { line -> when { line == "$ cd /" -> cur = root line == "$ cd .." -> cur = cur!!.parent!! line.startsWith("$ cd ") -> cur = cur!!.dirs.find { it.name == line.substring(5) }!! line == "$ ls" -> Unit line.startsWith("dir ") -> cur!!.dirs.add(Dir(line.substring(4), cur)) else -> line.split(" ", limit = 2).let { (size, name) -> cur!!.files.add(File(name, size.toInt())) } } } return root } fun part1(input: List<String>) = buildDirTree(input) .allDirs .map(Dir::size) .filter { it <= 100_000 } .sum() fun part2(input: List<String>): Int { val root = buildDirTree(input) val freeSpace = 70_000_000 - root.size val requiredAdditionalSpace = 30_000_000 - freeSpace return root .allDirs .map(Dir::size) .sorted() .find { it > requiredAdditionalSpace }!! } val testInput = readStrings("Day07_test") check(part1(testInput) == 95_437) val input = readStrings("Day07") println(part1(input)) check(part2(testInput) == 24_933_642) println(part2(input)) }
0
Kotlin
0
0
16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f
1,915
aoc-2022
Apache License 2.0
src/Day18.kt
cypressious
572,898,685
false
{"Kotlin": 77610}
fun main() { data class Cube(val x: Int, val y: Int, val z: Int) val sides = listOf( Cube(0, 0, 1), Cube(0, 0, -1), Cube(0, 1, 0), Cube(0, -1, 0), Cube(1, 0, 0), Cube(-1, 0, 0), ) fun parse(input: List<String>): Pair<List<Cube>, List<List<BooleanArray>>> { val cubes = input.map { line -> line.split(",").map(String::toInt).let { (x, y, z) -> Cube(x, y, z) } } val maxZ = cubes.maxOf { it.z } val maxY = cubes.maxOf { it.y } val maxX = cubes.maxOf { it.x } val space = List(maxZ + 1) { List(maxY + 1) { BooleanArray(maxX + 1) } } for ((x, y, z) in cubes) { space[z][y][x] = true } return cubes to space } fun part1(input: List<String>): Int { val (cubes, space) = parse(input) return cubes.sumOf { cube -> sides.count { side -> space.getOrNull(cube.z + side.z) ?.getOrNull(cube.y + side.y) ?.getOrNull(cube.x + side.x) != true } } } fun part2(input: List<String>): Int { val (cubes, space) = parse(input) val pockets = List(space.size) { List(space[0].size) { BooleanArray(space[0][0].size) } } fun isPocketOrStone(z: Int, y: Int, x: Int, visited: MutableSet<Cube>): Boolean { if (z !in pockets.indices || y !in pockets[z].indices || x !in pockets[z][y].indices) { return false } if (space[z][y][x]) { return true } // outer edge if (z == 0 || z == pockets.lastIndex || y == 0 || y == pockets[z].lastIndex || x == 0 || x == pockets[z][y].lastIndex) { return false } val cube = Cube(x, y, z) if (cube in visited) { return true } visited += cube return sides.all { (dz, dy, dx) -> isPocketOrStone(z + dz, y + dy, x + dx, visited) } } for (z in pockets.indices) { for (y in pockets[z].indices) { for (x in pockets[z][y].indices) { if (!space[z][y][x] && !pockets[z][y][x]) { val adjacent = mutableSetOf<Cube>() if (isPocketOrStone(z, y, x, adjacent)) { for (pocket in adjacent) { pockets[pocket.z][pocket.y][pocket.x] = true } } } } } } return cubes.sumOf { cube -> sides.count { side -> space.getOrNull(cube.z + side.z) ?.getOrNull(cube.y + side.y) ?.getOrNull(cube.x + side.x) != true && pockets.getOrNull(cube.z + side.z) ?.getOrNull(cube.y + side.y) ?.getOrNull(cube.x + side.x) != true } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
3,410
AdventOfCode2022
Apache License 2.0
src/day03/Day03.kt
wasabi-muffin
726,936,666
false
{"Kotlin": 10804}
package day03 import base.Day fun main() = Day03.run() object Day03 : Day<Int>("03") { override val test1Expected: Int = 4361 override val test2Expected: Int = 4678351 // override val part1Expected: Int = 532331 // override val part2Expected: Int = 823011201 override fun part1(input: List<String>): Int { val data = parse(input = input) return data.numbers.sumOf { number -> if (number.boundingBox.contains(symbols = data.symbols)) number.value else 0 } } override fun part2(input: List<String>): Int { val data = parse(input = input) return data.symbols.filter { it.value == '*' }.map { it.ratio(data.numbers) }.filter { it.count == 2 }.sumOf { it.value } } private fun parse(input: List<String>) = input.foldIndexed(Data()) { index, acc, line -> val newData = parseLine(index, line) acc.copy( numbers = acc.numbers + newData.numbers, symbols = acc.symbols + newData.symbols ) } private fun parseLine(lineNumber: Int, line: String): Data = line.foldIndexed(Metadata()) { index, metadata, c -> when { c.isDigit() && index == line.lastIndex -> metadata.copy( data = metadata.data.copy( numbers = metadata.updateNumbers( number = (metadata.number + c).toInt(), start = metadata.start ?: Point(x = index - 1, y = lineNumber), end = Point(x = index - 1, y = lineNumber) ) ), ) c.isDigit() && metadata.start != null -> metadata.copy(number = metadata.number + c) c.isDigit() && metadata.start == null -> metadata.copy(number = metadata.number + c, start = Point(x = index, y = lineNumber)) metadata.start != null -> metadata.copy( number = "", start = null, data = metadata.data.copy( numbers = metadata.updateNumbers( number = metadata.number.toInt(), start = metadata.start, end = Point(x = index - 1, y = lineNumber) ), symbols = metadata.updateSymbols(c = c, point = Point(x = index, y = lineNumber)) ) ) else -> metadata.copy(data = metadata.data.copy(symbols = metadata.updateSymbols(c = c, point = Point(x = index, y = lineNumber)))) } }.data } data class Metadata( val number: String = "", val start: Point? = null, val data: Data = Data(), ) { fun updateNumbers(number: Int, start: Point, end: Point) = this.data.numbers + Number(value = number, start = start, end = end) fun updateSymbols(c: Char, point: Point) = if (c != '.') this.data.symbols + Symbol(value = c, point = point) else this.data.symbols } data class Data( val numbers: List<Number> = emptyList(), val symbols: List<Symbol> = emptyList(), ) data class Point(val x: Int, val y: Int) data class Box(val start: Point, val end: Point) { fun contains(point: Point): Boolean = point.x >= start.x && point.y >= start.y && point.x <= end.x && point.y <= end.y fun contains(symbols: List<Symbol>): Boolean = symbols.any { contains(it.point) } } data class Number(val value: Int, val start: Point, val end: Point) { val boundingBox get() = Box( start = Point(start.x - 1, start.y - 1), end = Point(end.x + 1, end.y + 1) ) } data class Symbol(val value: Char, val point: Point) { fun ratio(numbers: List<Number>): Ratio = numbers.fold(initial = Ratio()) { ratio, number -> if (number.boundingBox.contains(point)) { Ratio(count = ratio.count + 1, value = ratio.value * number.value) } else { ratio } } inner class Ratio(val count: Int = 0, val value: Int = 1) }
0
Kotlin
0
0
544cdd359e4456a74b1584cbf1e5dddca97f1394
3,962
advent-of-code-2023
Apache License 2.0
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day20.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2020 import nl.dirkgroot.adventofcode.util.Input import nl.dirkgroot.adventofcode.util.Puzzle import kotlin.math.sqrt class Day20(input: Input) : Puzzle() { data class TileArrangement(val tileId: Long, val image: List<List<Char>>) private val tiles by lazy { input.string().split("\n\n").map { parseTile(it) }.toMap() } private fun parseTile(text: String): Pair<Long, List<List<Char>>> { val lines = text.split("\n") val id = lines[0].substring(5..8).toLong() return id to lines.subList(1, lines.size).map { it.map { c -> c } } } override fun part1() = arrange().let { grid -> grid[0][0].tileId * grid.last()[0].tileId * grid.last().last().tileId * grid[0].last().tileId } override fun part2() = permutations(imageFromGrid(arrange())) .map { it to findSeaMonsters(it) } .first { (_, monsters) -> monsters.isNotEmpty() } .let { (image, monsters) -> markSeaMonsters(image, monsters) } .sumOf { line -> line.count { c -> c == '#' } } private fun arrange(): List<List<TileArrangement>> { val gridSize = sqrt(tiles.keys.size.toDouble()).toInt() * 2 + 1 val tileIds = tiles.map { (id, _) -> id }.toMutableList() val grid = List(gridSize) { MutableList<TileArrangement?>(gridSize) { null } } val x = gridSize / 2 val y = x val tileId = tiles.keys.first() grid[y][x] = TileArrangement(tileId, tiles[tileId]!!) tileIds.remove(tileId) var fill = setOf(x to y) while (tileIds.isNotEmpty()) { fill = fill.filter { (x, y) -> grid[y][x] != null } .flatMap { (x, y) -> setOf(x - 1 to y, x + 1 to y, x to y - 1, x to y + 1) } .filter { (x, y) -> grid[y][x] == null } .toSet() .onEach { (x, y) -> val tilePermutations = tileIds.asSequence().flatMap { tileId -> permutations(tiles[tileId]!!).map { tile -> tileId to tile } } tilePermutations .firstOrNull { (_, permutation) -> (grid[y][x - 1]?.let { fitsHorizontally(it.image, permutation) } ?: false) || (grid[y][x + 1]?.let { fitsHorizontally(permutation, it.image) } ?: false) || (grid[y - 1][x]?.let { fitsVertically(it.image, permutation) } ?: false) || (grid[y + 1][x]?.let { fitsVertically(permutation, it.image) } ?: false) } ?.let { (id, tile) -> grid[y][x] = TileArrangement(id, tile) tileIds.remove(id) } } } return grid .filter { line -> line.any { tile -> tile != null } } .map { line -> line.filterNotNull() } } private fun permutations(image: List<List<Char>>) = sequence { var permutation = image for (i in 1..4) { permutation = rotateCW(permutation) yield(permutation) permutation = flipHorizontal(permutation) yield(permutation) permutation = flipVertical(permutation) yield(permutation) permutation = flipHorizontal(permutation) yield(permutation) permutation = flipVertical(permutation) } } private fun fitsHorizontally(tile1: List<List<Char>>, tile2: List<List<Char>>) = tile1.withIndex().all { (y, line) -> line.last() == tile2[y].first() } private fun fitsVertically(tile1: List<List<Char>>, tile2: List<List<Char>>) = tile1.last().withIndex().all { (x, c) -> tile2.first()[x] == c } private fun rotateCW(tile: List<List<Char>>) = transpose(tile, ::rotateXYCounterCW) private fun flipHorizontal(tile: List<List<Char>>) = transpose(tile, ::flipXYHorizontal) private fun flipVertical(tile: List<List<Char>>) = transpose(tile, ::flipXYVertical) private fun transpose(tile: List<List<Char>>, transformation: (Int, Int, Int) -> Pair<Int, Int>) = tile.indices.map { y -> tile[y].indices.map { x -> transformation(x, y, tile.size).let { (sx, sy) -> tile[sy][sx] } } } private fun rotateXYCounterCW(x: Int, y: Int, size: Int) = y to size - x - 1 private fun flipXYHorizontal(x: Int, y: Int, size: Int) = size - x - 1 to y private fun flipXYVertical(x: Int, y: Int, size: Int) = x to size - y - 1 private fun imageFromGrid(grid: List<List<TileArrangement>>) = grid .map { line -> line.map { arr -> TileArrangement(arr.tileId, arr.image .slice(1 until arr.image.lastIndex) .map { line -> line.slice(1 until line.lastIndex) }) } } .flatMap { gridLine -> gridLine[0].image.indices.map { y -> gridLine.flatMap { tile -> tile.image[y] } } } private val seaMosterWidth = 20 private val seaMosterHeight = 3 private val seaMonster = listOf( " # ", "# ## ## ###", " # # # # # # " ) private fun findSeaMonsters(image: List<List<Char>>) = sequence { for (y in 0..image.size - seaMosterHeight) { for (x in 0..image[y].size - seaMosterWidth) { if (isSeaMonster(image, x, y)) yield(x to y) } } }.toList() private fun isSeaMonster(image: List<List<Char>>, x: Int, y: Int) = seaMonster.withIndex().all { (monsterY, line) -> line.withIndex().all { (monsterX, c) -> when (c) { '#' -> image[y + monsterY][x + monsterX] == '#' else -> true } } } private fun markSeaMonsters(image: List<List<Char>>, monsters: List<Pair<Int, Int>>) = image.map { it.toMutableList() }.also { result -> monsters.forEach { (monsterX, monsterY) -> for (y in 0 until seaMosterHeight) { for (x in 0 until seaMosterWidth) { if (seaMonster[y][x] == '#') result[monsterY + y][monsterX + x] = 'O' } } } } }
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
6,447
adventofcode-kotlin
MIT License
aoc16/day_22/main.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
import pathutils.Pos import pathutils.fourNeighs import pathutils.shortest import java.io.File data class Node(val size: Int, val used: Int, var target: Boolean) fun parsePos(line: String): Pos = with(line.split(" ")[0].split("-")) { Pos(this[1].drop(1).toInt(), this[2].drop(1).toInt()) } fun parseNode(line: String): Node = with(line.split("\\s+".toRegex())) { Node(this[1].dropLast(1).toInt(), this[2].dropLast(1).toInt(), false) } fun fits(n1: Node, n2: Node): Boolean = n1 !== n2 && n1.used > 0 && n1.used <= n2.size - n2.used fun interchangeable(n1: Node, n2: Node): Boolean = n1.size > n2.used && n2.size > n1.used && !n1.target && !n2.target fun neighs(pos: Pos, nodes: Map<Pos, Node>): List<Pos> = fourNeighs(pos).filter { nodes[it] != null && interchangeable(nodes[it]!!, nodes[pos]!!) } fun main() { val nodes = File("input").readLines().drop(2).map { parsePos(it) to parseNode(it) }.toMap() val first = nodes .flatMap { (_, n1) -> nodes.map { (_, n2) -> n1 to n2 } } .filter { (n1, n2) -> fits(n1, n2) } .count() println("First: $first") val mainPath = nodes.keys.filter { it.y == 0 }.sortedBy { -it.x }.toMutableList() var target = mainPath.first() mainPath.removeFirst() nodes[target]!!.target = true var empty = nodes.filterValues { it.used == 0 }.keys.first() var totalLen = 0 while (!mainPath.isEmpty()) { val nextTarget = mainPath.first() mainPath.removeFirst() totalLen += shortest(empty, nextTarget, nodes, ::neighs)!!.len() + 1 nodes[target]!!.target = false nodes[nextTarget]!!.target = true empty = target target = nextTarget } println("Second: $totalLen") }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
1,741
advent-of-code
MIT License
src/Day04.kt
patrickwilmes
572,922,721
false
{"Kotlin": 6337}
private fun List<String>.buildRanges(): Pair<Set<Int>, Set<Int>> { val ranges = this.map { it.split("-").map { it.toInt() } } val firstRange = (ranges[0][0]..ranges[0][1]).toSet() val secondRange = (ranges[1][0]..ranges[1][1]).toSet() return firstRange to secondRange } // 513, 878 private fun List<String>.mapToRanges(): List<Pair<Set<Int>, Set<Int>>> = map { val parts = it.split(",") parts.buildRanges() } private fun oneSetIsFullyContainedInOther(it: Pair<Set<Int>, Set<Int>>) = it.first.intersect(it.second) == it.first || it.first.intersect(it.second) == it.second private fun setsOverlap(it: Pair<Set<Int>, Set<Int>>) = it.first.intersect(it.second).isNotEmpty() || it.first.intersect(it.second).isNotEmpty() fun main() { fun part1(input: List<String>): Int = input .mapToRanges() .filter(::oneSetIsFullyContainedInOther).size fun part2(input: List<String>): Int = input.mapToRanges() .filter(::setsOverlap).size val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
162c8f1b814805285e10ea4e3ab944c21e8be4c5
1,117
advent-of-code-2022
Apache License 2.0
src/Day04.kt
TheOnlyTails
573,028,916
false
{"Kotlin": 9156}
operator fun IntRange.contains(other: IntRange) = other.first in this && other.last in this infix fun IntRange.overlaps(other: IntRange) = other.first in this || other.last in this fun main() { fun part1(input: List<String>): Int { return input .map { val (range1, range2) = it.split(",") range1 to range2 } .map { (range1, range2) -> val (start1, end1) = range1.split("-").map(String::toInt) val (start2, end2) = range2.split("-").map(String::toInt) start1..end1 to start2..end2 } .count { (range1, range2) -> range1 in range2 || range2 in range1 } } fun part2(input: List<String>): Int { return input .map { val (range1, range2) = it.split(",") range1 to range2 } .map { (range1, range2) -> val (start1, end1) = range1.split("-").map(String::toInt) val (start2, end2) = range2.split("-").map(String::toInt) start1..end1 to start2..end2 } .count { (range1, range2) -> range1 overlaps range2 || range2 overlaps range1 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
685ce47586b6d5cea30dc92f4a8e55e688005d7c
1,547
advent-of-code-2022
Apache License 2.0
src/day02/Day02.kt
pnavais
727,416,570
false
{"Kotlin": 17859}
package day02 import readInput const val MAX_RED = 12L const val MAX_GREEN = 13L const val MAX_BLUE = 14L enum class Color(val maxNum: Long) { RED(MAX_RED), GREEN(MAX_GREEN), BLUE(MAX_BLUE) } data class BallInfo(val number: Long, val color: Color) { fun isValid() = number <= color.maxNum } fun getId(input: String): Long { val (gameInfo, subsets) = input.split(":") val gameId = gameInfo.split(" ")[1].trim().toLong() val isValid = subsets.split(";").none { s -> val ballsInfo = s.split(",").any { val (n, c) = it.trim().split(" ") !BallInfo(n.toLong(), Color.valueOf(c.uppercase())).isValid() } ballsInfo } return if (isValid) gameId else 0L } fun getPower(input: String): Long { val (_, subsets) = input.split(":") val totalBalls = mutableListOf<BallInfo>() subsets.split(";").forEach { s -> totalBalls.addAll(s.split(",").map { val (n, c) = it.trim().split(" ") BallInfo(n.toLong(), Color.valueOf(c.uppercase())) }) } val maxGreen = totalBalls.filter { it.color == Color.GREEN }.maxBy { ballInfo -> ballInfo.number }.number val maxRed = totalBalls.filter { it.color == Color.RED }.maxBy { ballInfo -> ballInfo.number }.number val maxBlue = totalBalls.filter { it.color == Color.BLUE }.maxBy { ballInfo -> ballInfo.number }.number return maxGreen * maxRed * maxBlue } fun part1(input: List<String>): Long { return input.sumOf(::getId) } fun part2(input: List<String>): Long { return input.sumOf(::getPower) } fun main() { val testInput = readInput("input/day02") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
f5b1f7ac50d5c0c896d00af83e94a423e984a6b1
1,699
advent-of-code-2k3
Apache License 2.0
src/Day12.kt
f1qwase
572,888,869
false
{"Kotlin": 33268}
private typealias HeightsMap = Map<Position, Char> private data class Input2( val heightsMap: HeightsMap, val start: Position, val finish: Position, ) private fun parseState(input: List<String>): Input2 { lateinit var position: Position lateinit var target: Position val heights = buildMap { input.forEachIndexed { y, line -> line .mapIndexed { x, char -> when (char) { 'S' -> 'a'.also { position = Position(x, y) } 'E' -> 'z'.also { target = Position(x, y) } in 'a'..'z' -> char else -> throw IllegalArgumentException("Unknown char $char") } } .forEachIndexed { x, char -> set(Position(x, y), char) } } } return Input2(heights, position, target) } fun main() { fun part1(input: List<String>): Int { val (heights, start, finish) = parseState(input) val visited = mutableSetOf(start) val positions = generateSequence(setOf(start)) { lastStepPositions -> if (lastStepPositions.isEmpty()) return@generateSequence null visited += lastStepPositions lastStepPositions.flatMap { position -> position.neighbours() .filter { it in heights } .filter { heights[it]!! - heights[position]!! <= 1 } }.toSet() - visited } return positions .take(10000) .indexOfFirst { it.contains(finish) } } fun part2(input: List<String>): Int { val (heights, start, finish) = parseState(input) val visited = mutableSetOf(start) val positions = generateSequence(heights.filterValues { it == 'a' }.keys) { lastStepPositions -> if (lastStepPositions.isEmpty()) return@generateSequence null visited += lastStepPositions lastStepPositions.flatMap { position -> position.neighbours() .filter { it in heights } .filter { heights[it]!! - heights[position]!! <= 1 } }.toSet() - visited } return positions .take(10000) .indexOfFirst { it.contains(finish) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") part1(testInput).let { check(it == 31) { it } } val input = readInput("Day12") println(part1(input)) part2(testInput).let { check(it == 29) { it } } println(part2(input)) }
0
Kotlin
0
0
3fc7b74df8b6595d7cd48915c717905c4d124729
2,748
aoc-2022
Apache License 2.0
src/adventofcode/day03/Day03.kt
bstoney
574,187,310
false
{"Kotlin": 27851}
package adventofcode.day03 import adventofcode.AdventOfCodeSolution fun main() { Solution.solve() } object Solution : AdventOfCodeSolution<Int>() { override fun solve() { solve(3, 157, 70) } override fun part1(input: List<String>): Int { return getIncorrectItems(input) .map(Item::priority) .sum() } override fun part2(input: List<String>): Int { return getGroupBadges(input) .map(Item::priority) .sum() } private fun getGroupBadges(input: List<String>) = getRucksacks(input) .chunked(3) .mapIndexed { index, rucksacks -> val badge = rucksacks.map(Rucksack::items) .reduce { acc, items -> acc.intersect(items) } .single() debug("Group $index -> $badge priority: ${badge.priority()}") badge } private fun getIncorrectItems(input: List<String>) = getRucksacks(input) .mapIndexed { index, rucksack -> val sharedItem = rucksack.sharedItem() debug("Rucksack $index -> $sharedItem priority: ${sharedItem.priority()}") sharedItem } private fun getRucksacks(input: List<String>): List<Rucksack> = input .map { it.map(::Item) } .map { val splitAt = it.size / 2 val compartment1Items = it.subList(0, splitAt).toSet() val compartment2Items = it.subList(splitAt, it.size).toSet() Rucksack(compartment1Items, compartment2Items) } data class Rucksack(val compartment1: Set<Item>, val compartment2: Set<Item>) { fun sharedItem() = compartment1.intersect(compartment2).single() fun items() = compartment1 + compartment2 } data class Item(val id: Char) { fun priority() = if (id >= 'a') id.code - 0x60 else id.code - 0x40 + 26 } }
0
Kotlin
0
0
81ac98b533f5057fdf59f08940add73c8d5df190
1,893
fantastic-chainsaw
Apache License 2.0
src/Day11.kt
zsmb13
572,719,881
false
{"Kotlin": 32865}
package day11 import readInput class Monkey( val items: MutableList<Long>, val op: (Long) -> Long, val divisor: Long, val targets: Pair<Int, Int>, ) { var inspections = 0L fun performRound(calm: (Long) -> Long) { while (true) { val item = items.removeFirstOrNull() ?: return val newItem = calm(op(item)).also { inspections++ } throwItemTo( target = if (newItem % divisor == 0L) targets.first else targets.second, item = newItem, ) } } companion object { fun parse(data: List<String>): Monkey { val (symbol, value) = data[2].substringAfter("new = old ").split(" ") return Monkey( items = data[1].substringAfter("items: ") .split(", ") .map(String::toLong) .toMutableList(), op = when (symbol) { "*" -> { if (value == "old") { old -> old * old } else { old -> old * value.toLong() } } "+" -> { { it + value.toLong() } } else -> error("Unexpected operation") }, divisor = data[3].substringAfter("by ").toLong(), targets = data[4].substringAfterLast(" ").toInt() to data[5].substringAfterLast(" ").toInt(), ) } } } var monkeys = listOf<Monkey>() fun throwItemTo(target: Int, item: Long) { monkeys[target].items += item } val List<Monkey>.monkeyBusiness get() = sortedByDescending(Monkey::inspections) .take(2) .let { (m1, m2) -> m1.inspections * m2.inspections } fun main() { fun runMonkeys( testInput: List<String>, iterations: Int, calming: (Long) -> Long ): Long { monkeys = testInput.chunked(7).map(Monkey::parse) repeat(iterations) { monkeys.forEach { monkey -> monkey.performRound(calm = calming) } } return monkeys.monkeyBusiness } fun part1(testInput: List<String>) = runMonkeys(testInput = testInput, iterations = 20, calming = { it / 3 }) fun part2(testInput: List<String>): Long { val calmingNumber = monkeys.fold(1L) { acc, monkey -> acc * monkey.divisor } return runMonkeys(testInput = testInput, iterations = 10_000, calming = { it % calmingNumber }) } val testInput = readInput("Day11_test") check(part1(testInput) == 10_605L) check(part2(testInput) == 2_713_310_158L) val input = readInput("Day11") check(part1(input).also(::println) == 56_595L) check(part2(input).also(::println) == 15_693_274_740L) }
0
Kotlin
0
6
32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35
2,767
advent-of-code-2022
Apache License 2.0
src/day12/day12.kt
bienenjakob
573,125,960
false
{"Kotlin": 53763}
package day12 import inputTextOfDay import testTextOfDay const val day = 12 val testInput = testTextOfDay(day) val input = inputTextOfDay(day) typealias Maze = List<MutableList<Int>> typealias Cell = Pair<Int, Int> fun main() { val maze = createMazeOfInts(input)//.also { printMaze(it) } val start = findSingleInMaze(input, 'S')//.also { println("Start: ${it.first} to ${it.second}") } val goal = findSingleInMaze(input, 'E')//.also { println("End: ${it.first} to ${it.second}") } val allNeighbours = createListsOfNeighbours(maze) val reachable = createListsOfReachableNeighbours(maze, allNeighbours) // part1 val distance: Int = distanceOfShortestPath(setOf(start), goal, reachable, setOf(), 0) println(distance) // part2 val possibleStarts = findAllInMaze(input, 'a') union setOf(start) val minDistance: Int = distanceOfShortestPath(possibleStarts, goal, reachable, setOf(), 0) println(minDistance) } fun distanceOfShortestPath(starts: Set<Cell>, goal: Cell, neighbours: Map<Cell, List<Cell>>, visited: Set<Cell>, length: Int): Int { fun distanceOfShortestPath(starts: Set<Cell>, visited: Set<Cell>, length: Int): Int { val nextStart = mutableSetOf<Cell>() val nextLength = length + 1 val nextVisited = visited union starts if (starts.isEmpty()) error("(${goal.first}, ${goal.second}) not reachable") starts.forEach { cell -> val cellNeighbours = neighbours.getOrDefault(cell, emptyList()) if (goal in cellNeighbours) return nextLength.also{ println(starts.size)} nextStart.addAll(cellNeighbours) } return distanceOfShortestPath(nextStart, nextVisited, nextLength) } return distanceOfShortestPath(starts, visited, length) } fun createListsOfNeighbours(maze: Maze): Map<Cell, List<Cell>> { val neighbours = mutableMapOf<Cell, MutableList<Cell>>() maze.forEachIndexed { r, row -> for (c in row.indices) { val cell: Cell = r to c neighbours[cell] = mutableListOf() if (c + 1 < row.size) neighbours[cell]!!.add(r to c + 1) if (c - 1 >= 0) neighbours[cell]!!.add(r to c - 1) if (r + 1 < maze.size) neighbours[r to c]!!.add(r + 1 to c) if (r - 1 >= 0) neighbours[cell]!!.add(r - 1 to c) } } return neighbours } fun createListsOfReachableNeighbours(maze: Maze, neighbours: Map<Cell, List<Cell>>): Map<Cell, List<Cell>> { val reachableNeighbours = mutableMapOf<Cell, MutableList<Cell>>() maze.forEachIndexed { r, row -> for (c in row.indices) { val currentCell: Cell = r to c reachableNeighbours[currentCell] = mutableListOf() neighbours[currentCell]!!.forEach { neighbour -> if (neighbourIsReachable(currentCell, neighbour, maze)) reachableNeighbours[currentCell]!!.add(neighbour) } } } return reachableNeighbours } private fun neighbourIsReachable(currentCell: Cell, neighbour: Cell, maze: Maze) = maze[currentCell.first][currentCell.second] >= maze[neighbour.first][neighbour.second] - 1 fun findSingleInMaze(input: String, char: Char): Cell { return findAllInMaze(input, char).single() } fun findAllInMaze(input: String, char: Char): Set<Cell> { val result = mutableSetOf<Cell>() val rows = input.lines() rows.forEachIndexed { r, row -> for (c in row.indices) { if (rows[r][c] == char) result.add(r to c) } } return result } fun createMazeOfInts(input: String): Maze { val rows = input.lines() val dy = rows.size val dx = rows.first().length val maze = createEmptyMaze(dx, dy, 0) maze.forEachIndexed { r, row -> for (c in row.indices) { val inputValue = rows[r][c] maze[r][c] = when (inputValue) { 'S' -> 'a' - 'a' 'E' -> 'z' - 'a' in 'a'..'z' -> inputValue - 'a' else -> error("$inputValue") } } } return maze } @Suppress("unused") fun printMaze(maze: Maze) { maze.forEach { row -> row.forEach { value -> print("$value".padStart(2, ' ')) } println("") } } fun createEmptyMaze(dx: Int, dy: Int, defaultValue: Int = 0): Maze { return List(dy) { MutableList(dx) { defaultValue } } }
0
Kotlin
0
0
6ff34edab6f7b4b0630fb2760120725bed725daa
4,401
aoc-2022-in-kotlin
Apache License 2.0
src/Day05.kt
qmchenry
572,682,663
false
{"Kotlin": 22260}
fun main() { fun loadInitialPositions(input: List<String>): List<String> { val asRead = input .takeWhile { it.isNotBlank() } .filter { it.contains("[") } .map { it.chunked(4) .map { it[1] } } val longest = asRead.maxOfOrNull { it.size } ?: 0 val transposed = (0 until longest) .map { i -> asRead.map { it.getOrNull(i) ?: "" }.joinToString("") } .map { it.reversed().trim() } return transposed } fun rearrange(stacks: List<String>, input: List<String>, multiLift: Boolean = false): List<String> { val localStacks = stacks.toMutableList() val movements = input .filter { it.startsWith("move") } .map { it.split(" ").mapNotNull { it.toIntOrNull() } } movements.forEach { (qty, from, to) -> val toMove = localStacks[from - 1].takeLast(qty) localStacks[to - 1] = (localStacks.elementAtOrNull(to - 1) ?: " ") + if (multiLift) toMove else toMove.reversed() localStacks[from - 1] = localStacks[from - 1].dropLast(qty) } return localStacks } fun rearrange(input: List<String>, multiLift: Boolean): String { val stacks = loadInitialPositions(input) val rearranged = rearrange(stacks, input, multiLift = multiLift) return rearranged.map { it.takeLast(1) }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_sample") check(rearrange(testInput, false) == "CMZ") check(rearrange(testInput, true) == "MCD") val realInput = readInput("Day05_input") println("Part 1: ${rearrange(realInput, false)}") println("Part 2: ${rearrange(realInput, true)}") }
0
Kotlin
0
0
2813db929801bcb117445d8c72398e4424706241
1,869
aoc-kotlin-2022
Apache License 2.0
src/Day07.kt
iownthegame
573,926,504
false
{"Kotlin": 68002}
class Directory(val dirName: String) { private var files = arrayOf<File>() private var directories = arrayOf<Directory>() var dirSize: Int = 0 fun calculateSize() { println("calculate dir size $dirName") directories.forEach { it.calculateSize() } dirSize = files.sumOf { it.fileSize } + directories.sumOf { it.dirSize } println("calculated dir size $dirName is $dirSize") } fun getAllDirs(): Array<Directory> { var allDirs = arrayOf<Directory>(*directories) directories.forEach { allDirs = allDirs.plus(it.getAllDirs()) } return allDirs } fun addDir(directory: Directory) { println("add dir: ${directory.dirName}, current dir: ${dirName}") directories += directory } fun findDir(dirName: String): Directory { return directories.find { it.dirName == dirName }!! } fun addFile(file: File) { println("add file: ${file.fileName}, size: ${file.fileSize}, current dir: $dirName") files += file } } class File(val fileName: String, val fileSize: Int) { } fun main() { fun parseDirs(input: List<String>): Directory { val rootDir = Directory("/") var dirStacks = mutableListOf<Directory>(rootDir) for (line in input) { if (line[0].toString() == "$") { val splits = line.split(" ") val command = splits[1] if (command == "cd") { val goToDirName = splits[2] if (goToDirName == "/") { dirStacks = mutableListOf<Directory>(rootDir) } else if (goToDirName == "..") { dirStacks.removeLast() } else { val currentDir = dirStacks.last() dirStacks += currentDir.findDir(goToDirName) } } else if (command == "ls") { continue } } else { // content of ls command of currentDir val currentDir = dirStacks.last() if (line.substring(0, 3) == "dir") { val dirName = line.split(" ")[1] currentDir.addDir(Directory(dirName)) } else { val splits = line.split(" ") val fileSize = splits[0] val fileName = splits[1] currentDir.addFile(File(fileName, fileSize.toInt())) } } } rootDir.calculateSize() return rootDir } fun part1(input: List<String>): Int { val rootDir = parseDirs(input) val allDirs = rootDir.getAllDirs() val dirAtMostSize = 100000 return allDirs.filter { it.dirSize <= dirAtMostSize }.sumOf { it.dirSize } } fun part2(input: List<String>): Int { val rootDir = parseDirs(input) val totalDiskSpace = 70000000 val requiredUnusedSpace = 30000000 val unusedSpace = totalDiskSpace - rootDir.dirSize val deletedSpace = requiredUnusedSpace - unusedSpace val allDirSizes = rootDir.getAllDirs().map { it.dirSize }.sorted() for (dirSize in allDirSizes) { if (dirSize >= deletedSpace) { return dirSize } } return -1 } // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day07_sample") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readTestInput("Day07") println("part 1 result: ${part1(input)}") println("part 2 result: ${part2(input)}") }
0
Kotlin
0
0
4e3d0d698669b598c639ca504d43cf8a62e30b5c
3,737
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/jackchapman/adventofcode/Day07.kt
crepppy
317,691,375
false
null
package com.jackchapman.adventofcode fun solveDay7(): Pair<Int, Int> { val rules = getInput(7) val colorMap = parseBagRules(rules) val numberOfBagsThatHold = colorMap.keys.count { canContainBag("shiny gold", it, colorMap) } return numberOfBagsThatHold to numberOfContainedBags("shiny gold", colorMap) } // Completed parseBagRules and canContainBag in 17mins 8seconds fun canContainBag(findBag: String, curBag: String, bags: Map<String, List<Pair<Int, String>>>): Boolean { if (bags[curBag]!!.any { it.second == findBag }) return true if (bags[curBag]!!.isEmpty()) return false return bags[curBag]!!.any { canContainBag(findBag, it.second, bags) } } fun parseBagRules(rules: List<String>): Map<String, List<Pair<Int, String>>> { val bagRegex = Regex("(\\d+) ([\\w\\s]+) bags?") val colorMap: MutableMap<String, List<Pair<Int, String>>> = mutableMapOf() rules.forEach { val color = it.substringBefore("bags").trim() if (it.endsWith("no other bags.")) colorMap[color] = emptyList() else { colorMap[color] = bagRegex.findAll(it) .map { colorMatch -> colorMatch.groupValues[1].toInt() to colorMatch.groupValues[2] }.toList() } } return colorMap } // Completed in 7mins 8seconds fun numberOfContainedBags(bag: String, rules: Map<String, List<Pair<Int, String>>>): Int { return rules[bag]!!.sumBy { it.first + it.first * numberOfContainedBags(it.second, rules) } }
0
Kotlin
0
0
b49bb8f62b4542791626950846ca07d1eff4f2d1
1,490
aoc2020
The Unlicense
src/Day03.kt
nielsz
573,185,386
false
{"Kotlin": 12807}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { line -> line.compartments().getNonUniqueValues().getPriority() } } fun part2(input: List<String>): Int { return input .windowed(size = 3, step = 3) .sumOf { group -> getNonUniqueValues(group).first().getNumericValue() } } val input = readInput("Day03") println(part1(input)) // 7428 println(part2(input)) // 2650 } typealias Rucksack = String typealias Compartment = String fun Rucksack.compartments(): Pair<Compartment, Compartment> { return Pair(substring(0, length / 2), substring(length / 2)) } fun getNonUniqueValues(group: List<String>): Set<Char> { val result = hashSetOf<Char>() for (c in group[0]) { result.add(c) } for (i in 1..group.lastIndex) { val rucksack = group[i] for (c in result.clone() as Set<Char>) { if (!rucksack.contains(c)) result.remove(c) } } return result } private fun Pair<Compartment, Compartment>.getNonUniqueValues(): Set<Char> { val result = hashSetOf<Char>() val firstC = first.toSet() val secondC = second.toSet() for (c in firstC) { if (secondC.contains(c)) result.add(c) } for (c in secondC) { if (firstC.contains(c)) result.add(c) } return result } private fun Set<Char>.getPriority() = sumOf { it.getNumericValue() }
0
Kotlin
0
0
05aa7540a950191a8ee32482d1848674a82a0c71
1,482
advent-of-code-2022
Apache License 2.0
src/Day08.kt
kpilyugin
572,573,503
false
{"Kotlin": 60569}
import java.lang.Integer.max fun main() { fun List<Int>.indicesOfVisible(): List<Int> { return indices.filter { cur -> indices.all { it <= cur || get(it) < get(cur) } || indices.all { it >= cur || get(it) < get(cur) } } } fun part1(input: List<String>): Int { val table = input.map { line -> line.map { it.digitToInt() } } val n = table.size val m = table[0].size val d = Array(n) { IntArray(m) } for (i in 0 until n) { for (j in table[i].indicesOfVisible()) { d[i][j] = 1 } } for (j in 0 until m) { val column = table.map { it[j] } for (i in column.indicesOfVisible()) { d[i][j] = 1 } } return d.sumOf { it.sum() } } fun part2(input: List<String>): Int { val table = input.map { line -> line.map { it.digitToInt() } } val n = table.size val m = table[0].size var res = 0 for (i in 0 until n) { for (j in 0 until m) { fun canSee(dx: Int, dy: Int): Int { var x = i var y = j var visible = 0 while (true) { val x1 = x + dx val y1 = y + dy if (x1 in 0 until n && y1 in 0 until m) { visible++ if (table[x1][y1] < table[i][j]) { x = x1 y = y1 } else { return visible } } else { return visible } } } res = max(res, canSee(0, 1) * canSee(1, 0) * canSee(-1, 0) * canSee(0, -1) ) } } return res } val testInput = readInputLines("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInputLines("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7f0cfc410c76b834a15275a7f6a164d887b2c316
2,299
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/days/day16/Day16.kt
Stenz123
694,797,878
false
{"Kotlin": 27460}
package days.day16 import days.Day import java.util.LinkedList class Day17 : Day() { override fun partOne(): Any { val input = readInput() val rules = parseRules() val tickets = parseTickets() val ranges = rules.map { it.range }.flatten() val invalidValues = tickets.map { ticket -> ticket.filter { value -> ranges.none { range -> range.contains(value) } } }.flatten() return invalidValues.sum() } private fun parseTickets(): ArrayList<List<Int>> { //7,3,47 val unparsed = readInput().takeLastWhile { it != "nearby tickets:" } println(unparsed) val result = arrayListOf<ArrayList<Int>>() unparsed.forEach { val split = it.split(",") var ticket = arrayListOf<Int>() split.forEach { s -> ticket.add(s.toInt()) } result.add(ticket) } return ArrayList(result) } fun parseRules(): ArrayList<Rule> { val rulesUnparsed = readInput().takeWhile { it.isNotBlank() } val rules = arrayListOf<Rule>() rulesUnparsed.forEach { val nameValues = ArrayList(it.split(":")) val restult = Rule(nameValues[0], arrayListOf()) val split = nameValues[1].split(" or ").map { it.trim() } for (s in split) { val values = s.split("-") restult.range.add(IntRange(values[0].toInt(), values[1].toInt())) } rules.add(restult) } return rules } override fun partTwo(): Any { val input = readInput() val rules = parseRules() val tickets = parseTickets() val ranges = rules.map { it.range }.flatten() val validTickets = tickets.filter { ticket -> ticket.all { value -> ranges.any { range -> range.contains(value) } } } val possibleRulePositions = HashMap<Rule, ArrayList<Int>>() for (rule in rules) { for (i in 0..<validTickets[0].size) if (validTickets.all { rule.range.any { range -> range.contains(it[i]) } }) { if (possibleRulePositions[rule] == null) { possibleRulePositions[rule] = ArrayList() } possibleRulePositions[rule]?.add(i) } } val myTicketRaw = readInput().takeLastWhile { it != "your ticket:" }.first().split(",").map { it.toInt() } var result = 1 val combinations = findCombinations(possibleRulePositions) findCombinations(possibleRulePositions).forEach { (rule, position) -> println("${rule.identifier} at position $position") if (rule.identifier.startsWith("departure")){ println("Found departure rule: $rule at position $position") result *=myTicketRaw[position] } } return result } fun findCombinations(map: Map<Rule, List<Int>>): Map<Rule, Int> { val keys = map.keys.toList() val result = mutableMapOf<Rule, Int>() fun backtrack(index: Int, currentAssignment: MutableMap<Rule, Int>) { if (index == keys.size) { result.putAll(currentAssignment) return } val currentKey = keys[index] val possiblePositions = map[currentKey] ?: emptyList() for (position in possiblePositions) { if (!currentAssignment.values.contains(position)) { currentAssignment[currentKey] = position backtrack(index + 1, currentAssignment) currentAssignment.remove(currentKey) } } } backtrack(0, mutableMapOf()) return result } } class Rule(val identifier: String, val range: ArrayList<IntRange>) { override fun toString(): String { return "Rule(identifier='$identifier', range=$range)" } }
0
Kotlin
0
0
3e5ee86cd723c293ec44b1be314697ccf5cdaab7
4,172
advent-of-code-2020
The Unlicense
src/Day09.kt
sbaumeister
572,855,566
false
{"Kotlin": 38905}
import kotlin.math.abs fun moveKnot(knot: Pair<Int, Int>, knotToFollow: Pair<Int, Int>): Pair<Int, Int> { val xDiff = knotToFollow.first - knot.first val yDiff = knotToFollow.second - knot.second var (xNew, yNew) = knot if (abs(xDiff) + abs(yDiff) >= 3) { xNew = if (xDiff > 0) knot.first + 1 else knot.first - 1 yNew = if (yDiff > 0) knot.second + 1 else knot.second - 1 } if (abs(xDiff) == 2 && yDiff == 0) { xNew = if (xDiff > 0) knot.first + 1 else knot.first - 1 } if (xDiff == 0 && abs(yDiff) == 2) { yNew = if (yDiff > 0) knot.second + 1 else knot.second - 1 } return xNew to yNew } fun main() { fun part1(input: List<String>): Int { var head = 0 to 0 var tail = 0 to 0 val tailPositions = mutableSetOf<Pair<Int, Int>>() tailPositions.add(tail) input.forEach { line -> val direction = line.substring(0, 1) val steps = line.substring(2).toInt() repeat(steps) { when (direction) { "R" -> head = head.first + 1 to head.second "L" -> head = head.first - 1 to head.second "U" -> head = head.first to head.second + 1 "D" -> head = head.first to head.second - 1 } tail = moveKnot(tail, head) tailPositions.add(tail) } } return tailPositions.size } fun part2(input: List<String>): Int { var head = 0 to 0 val knots = (1..9).map { 0 to 0 }.toMutableList() val tailPositions = mutableSetOf<Pair<Int, Int>>() tailPositions.add(knots.last()) input.forEach { line -> val direction = line.substring(0, 1) val steps = line.substring(2).toInt() repeat(steps) { when (direction) { "R" -> head = head.first + 1 to head.second "L" -> head = head.first - 1 to head.second "U" -> head = head.first to head.second + 1 "D" -> head = head.first to head.second - 1 } repeat(knots.size) { i -> val leadingKnot = if (i == 0) head else knots[i - 1] knots[i] = moveKnot(knots[i], leadingKnot) } tailPositions.add(knots.last()) } } return tailPositions.size } val part1 = part1(readInput("Day09_test")) check(part1 == 13) val part2 = part2(readInput("Day09_test2")) check(part2 == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84
2,712
advent-of-code-2022
Apache License 2.0
src/Day23.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
fun <T> ArrayDeque<T>.rotate(times: Int = 1) = repeat(times) { addLast(removeFirst()) } fun <T> Iterable<T>.duplicates() = groupingBy(::identity).eachCount().filterValues { it > 1 }.keys fun <T : Comparable<T>> Iterable<T>.minmax(): Pair<T, T> { val iter = iterator() val first = iter.next() return iter.asSequence().fold(first to first) { (minSoFar, maxSoFar), element -> minOf(minSoFar, element) to maxOf(maxSoFar, element) } } fun boundingBox(points: Iterable<Point>): PointRegion { val iter = points.iterator() val first = iter.next() val (minCorner, maxCorner) = iter.asSequence().fold(first to first) { (minSoFar, maxSoFar), element -> Pair( Point(minOf(minSoFar.x, element.x), minOf(minSoFar.y, element.y)), Point(maxOf(maxSoFar.x, element.x), maxOf(maxSoFar.y, element.y)), ) } return PointRegion(minCorner, maxCorner) } enum class CardinalDirection(val adjacent: List<Point>) { N(listOf(Point(0, -1), Point(1, -1), Point(-1, -1))), S(listOf(Point(0, 1), Point(1, 1), Point(-1, 1))), W(listOf(Point(-1, 0), Point(-1, -1), Point(-1, 1))), E(listOf(Point(1, 0), Point(1, -1), Point(1, 1))); fun neighbors(point: Point) = adjacent.map(point::plus) } //private fun Point.allNeighbors() = CardinalDirection.values().flatMap { it.neighbors(this) }.distinct() fun Point.adjacent() = listOf( Point(0, -1), Point(1, -1), Point(1, 0), Point(1, 1), Point(0, 1), Point(-1, 1), Point(-1, 0), Point(-1, -1), ).map(::plus) fun main() { val grove = mutableSetOf<Point>() readInput("Day23").forEachIndexed { row, line -> line.forEachIndexed { column, char -> if (char == '#') { grove.add(Point(column, row)) } } } val directions = ArrayDeque(CardinalDirection.values().toList()) var moved = true var completedRounds = 0 while (moved) { if (completedRounds == 10) { val boundingBox = boundingBox(grove) val emptyGround = boundingBox.size - grove.size println(emptyGround) } moved = false val proposals = buildList { grove.forEach { elf -> if (elf.adjacent().any(grove::contains)) { for (direction in directions) { val neighbors = direction.neighbors(elf) if (neighbors.all { it !in grove }) { val proposal = neighbors.first() add(elf to proposal) break } } } } } val duplicateProposals = proposals.map { it.second }.duplicates() proposals.forEach { (elf, proposal) -> if (proposal !in duplicateProposals) { grove.remove(elf) grove.add(proposal) moved = true } } directions.rotate() completedRounds++ } println(completedRounds) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
3,096
advent-of-code-2022
Apache License 2.0
src/Day04.kt
GreyWolf2020
573,580,087
false
{"Kotlin": 32400}
fun main() { fun part1(input: List<String>): Int = input .contains(::fullyContains) fun part2(input: List<String>): Int = input .contains(::partiallyContains) // test if implementation meets criteria from the description, like: // val testInput = readInput("Day04_test") // check(part1(testInput) == 2) // // check(part2(testInput) == 4) // // val input = readInput("Day04") // println(part1(input)) // println(part2(input)) } fun List<String>.contains(fullyOrPartialContains: (List<Int>, List<Int>) -> Boolean) = map { it .split(",") } .foldRight(0) { cleaningAreas, containedAreas -> val (cleaningAreaOne, cleaningAreaTwo) = cleaningAreas .map { cleaningArea -> cleaningArea .split("-") .map { it.toInt() } } containedAreas + if (fullyOrPartialContains(cleaningAreaOne, cleaningAreaTwo)) 1 else 0 } fun fullyContains(areaOne: List<Int>, areaTwo: List<Int>): Boolean = when { areaOne.first() >= areaTwo.first() && areaOne.last() <= areaTwo.last() || areaTwo.first() >= areaOne.first() && areaTwo.last() <= areaOne.last() -> true else -> false } fun partiallyContains(areaOne: List<Int>, areaTwo: List<Int>): Boolean = (areaOne.first() .. areaOne.last()).toSet().intersect((areaTwo.first() .. areaTwo.last()).toSet()).size >= 1
0
Kotlin
0
0
498da8861d88f588bfef0831c26c458467564c59
1,424
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/me/grison/aoc/y2022/Day16.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2022 import me.grison.aoc.* import kotlin.math.max import kotlin.math.min class Day16 : Day(16, 2022) { override fun title() = "Proboscidea Volcanium" override fun partOne(): Int { val valves = parseValves() val distances = findAllDistances(valves) return solve(valves, distances, 30, elephant = false) } override fun partTwo(): Int { val valves = parseValves() val distances = findAllDistances(valves) return solve(valves, distances, 26, elephant = true) } private fun parseValves(): Valves { val valves = mutableMapOf<String, Valve>() inputList.forEach { val flow = it.allInts().first() val name = it.after("Valve ").before(" has") val destinations = (if (it.contains("valves ")) it.after("valves ").normalSplit(", ") else it.after("valve ").normalSplit(", ")).reversed() valves[name] = Valve(name, flow, destinations) } return valves } private fun findAllDistances(valves: Valves): Distances { val distances = mutableMapOf<Pair<String, String>, Int>() val combinations = valves.values.pairCombinations() combinations.forEach { (v1, v2) -> distances[p(v1.name, v2.name)] = if (v1.name == v2.name) 0 else 100 } repeat(valves.size) { combinations.forEach { (v1, v2) -> v1.destinations.forEach { distances[p(it, v2.name)] = min(distances[p(it, v2.name)]!!, distances[p(v1.name, v2.name)]!! + 1) } } } return distances } private fun solve(valves: Valves, distances: Distances, totalMinutes: Int, elephant: Boolean = false): Int { val nonNulls = valves.values.filter { it.flow > 0 }.map { it.name } val alternatives = mutableMapOf<Set<String>, Int>() fun findMostPressure(valveName: String, minutes: Int, pressure: Int = 0, seen: MutableSet<String> = mutableSetOf(), elephant: Boolean = false): Int { var (currentPressure, minutesRemaining) = p(pressure, minutes) // done if (minutes <= 1) { if (!elephant) return pressure else { val currentSeen = seen.toSet() if (seen in alternatives) return pressure + alternatives[currentSeen]!! else { alternatives[currentSeen] = findMostPressure("AA", totalMinutes, 0, seen, false) // restart return pressure + alternatives[currentSeen]!! } } } val currentValve = valves[valveName]!! // open valve if (currentValve.flow > 0) { minutesRemaining -= 1 currentPressure += minutesRemaining * currentValve.flow } var totalPressure = currentPressure nonNulls.forEach { nextValveName -> if (nextValveName !in seen) { seen.add(nextValveName) // maximize pressure val minutesArrived = minutesRemaining - distances[p(valveName, nextValveName)]!! totalPressure = max( findMostPressure(nextValveName, minutesArrived, currentPressure, seen, elephant), totalPressure ) seen.remove(nextValveName) } } return totalPressure } return findMostPressure("AA", totalMinutes, elephant = elephant) } } class Valve(val name: String, val flow: Int, val destinations: List<String>) typealias Valves = Map<String, Valve> typealias Distances = Map<Pair<String, String>, Int>
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
3,841
advent-of-code
Creative Commons Zero v1.0 Universal
src/Day13.kt
vjgarciag96
572,719,091
false
{"Kotlin": 44399}
private sealed interface Element { data class Integer(val value: Int) : Element data class List(val value: ArrayList<Element>) : Element companion object { fun newList(): Element { return List(ArrayList()) } } } private fun ArrayList<Element>.addAtDepth(element: Element, depth: Int) { var lastAtDepth: ArrayList<Element> = this var currentDepth = 0 while (currentDepth < depth) { lastAtDepth = (lastAtDepth.last() as Element.List).value currentDepth++ } lastAtDepth.add(element) } private fun Element.compareTo(other: Element): Int { if (this is Element.Integer && other is Element.Integer) { return value.compareTo(other.value) } else if (this is Element.List && other is Element.Integer) { return this.compareTo(Element.List(arrayListOf(other))) } else if (this is Element.Integer && other is Element.List) { return Element.List(arrayListOf(this)).compareTo(other) } else if (this is Element.List && other is Element.List) { var index = 0 val limit = minOf(this.value.size, other.value.size) while (index < limit) { val itemComp = this.value[index].compareTo(other.value[index]) if (itemComp != 0) return itemComp index++ } return this.value.size.compareTo(other.value.size) } else { error("Unreachable path") } } private fun parsePacket(rawPacket: String): ArrayList<Element> { val elements = ArrayList<Element>() var depth = 0 var index = 1 while (index < rawPacket.length - 1) { when (val char = rawPacket[index]) { '[' -> { elements.addAtDepth(Element.newList(), depth) depth++ } ']' -> depth-- ',' -> Unit else -> { var number = char.digitToInt() var nextDigit = rawPacket.getOrNull(index + 1) while (nextDigit != null && nextDigit.isDigit()) { number = number * 10 + nextDigit.digitToInt() index++ nextDigit = rawPacket.getOrNull(index + 1) } elements.addAtDepth(Element.Integer(number), depth) } } index++ } return elements } private fun part1(input: List<String>): Int { return input.chunked(3) { (packet1, packet2) -> parsePacket(packet1) to parsePacket(packet2) }.foldIndexed(initial = 0) { index, acc, (packet1, packet2) -> if (Element.List(packet1).compareTo(Element.List(packet2)) <= 0) { acc + index + 1 } else { acc } } } private fun part2(input: List<String>): Int { val sortedPackets = (input + listOf("[[2]]", "[[6]]")) .filter { line -> line.isNotEmpty() } .map { rawPacket -> parsePacket(rawPacket) } .sortedWith { packet1, packet2 -> Element.List(packet1).compareTo(Element.List(packet2)) } return (sortedPackets.indexOf(arrayListOf(Element.List(arrayListOf(Element.Integer(2))))) + 1) * (sortedPackets.indexOf(arrayListOf(Element.List(arrayListOf(Element.Integer(6))))) + 1) } fun main() { 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
ee53877877b21166b8f7dc63c15cc929c8c20430
3,447
advent-of-code-2022
Apache License 2.0
src/Day14.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
fun main() { val day = 14 data class Coord(val x: Int, val y: Int) { fun to(end: Coord): List<Coord> { val minX = minOf(x, end.x) val minY = minOf(y, end.y) val maxX = maxOf(x, end.x) val maxY = maxOf(y, end.y) return (minX..maxX).flatMap { nx -> (minY..maxY).map { ny -> Coord(nx, ny) } } } val left get() = Coord(this.x - 1, this.y + 1) val right get() = Coord(this.x + 1, this.y + 1) } fun String.toPos() = this.split(",") .let { Coord(it[0].toInt(), it[1].toInt()) } fun List<List<Char>>.fallTo(p: Coord, height: Boolean = false): Coord? { var y = p.y + 1 val col = this[p.x]; return (y until col.size).firstOrNull { col[it] != '.'} ?.let { Coord(p.x, it - 1) } ?: if (height) Coord(p.x, col.size - 1) else null } fun List<List<Char>>.notBlocked(p: Coord) = p.x < this.size && p.y < this[p.x].size && this[p.x][p.y] == '.' fun List<MutableList<Char>>.sand(p: Coord) = this[p.x].set(p.y, 'o') fun MutableList<MutableList<Char>>.pourSand(height: Boolean = false): Int { val start = Coord(500, -1) var sand = 0 var cur = this.fallTo(start, height) while (cur != start) { if (cur == null) return sand cur = when { this.notBlocked(cur.left) -> this.fallTo(cur.left, height) this.notBlocked(cur.right) -> this.fallTo(cur.right, height) else -> { this.sand(cur) sand++ this.fallTo(start, height) } } } return sand } fun parseInput(input: List<String>): MutableList<MutableList<Char>> { val points = input.flatMap { line -> line.split(" -> ") .map { it.toPos() } .windowed(2) .flatMap { it[0].to(it[1]) } .distinct() } val maxY = points.maxOf { it.y } val maxX = points.maxOf { it.x } + maxY val data: MutableList<MutableList<Char>> = MutableList(maxX + 2) { MutableList(maxY + 2) { '.' } } points.forEach { (x, y) -> data[x][y] = '#' } return data } fun part1(input: List<String>) = parseInput(input) .pourSand() fun part2(input: List<String>) = parseInput(input) .pourSand(true) // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day.pad(2)}_test") checkTest(24) { part1(testInput) } checkTest(93) { part2(testInput) } val input = readInput("Day${day.pad(2)}") solution { part1(input) } solution { part2(input) } }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
2,847
aoc22
Apache License 2.0
src/Day18.kt
davidkna
572,439,882
false
{"Kotlin": 79526}
import kotlin.collections.ArrayDeque fun main() { fun parseInput(input: List<String>) = input.map { val (x, y, z) = it.split(",").map { n -> n.toInt() } Triple(x, y, z) }.toList() val directions = listOf( Triple(1, 0, 0), Triple(-1, 0, 0), Triple(0, 1, 0), Triple(0, -1, 0), Triple(0, 0, 1), Triple(0, 0, -1), ) fun part1(input: List<String>): Int { val cubes = parseInput(input) val map = hashSetOf(*cubes.toTypedArray()) return cubes.flatMap { cube -> directions.map { Triple( cube.first + it.first, cube.second + it.second, cube.third + it.third, ) } }.count { it !in map } } fun part2(input: List<String>): Int { val cubes = parseInput(input) val map = hashSetOf(*cubes.toTypedArray()) val maxX = cubes.maxBy { it.first }.first + 1 val minX = cubes.minBy { it.first }.first - 1 val maxY = cubes.maxBy { it.second }.second + 1 val minY = cubes.minBy { it.second }.second - 1 val maxZ = cubes.maxBy { it.third }.third + 1 val minZ = cubes.minBy { it.third }.third - 1 val start = Triple(minX, minY, minZ) val visited: HashSet<Triple<Int, Int, Int>> = hashSetOf() val q = ArrayDeque<Triple<Int, Int, Int>>() q.add(start) var out = 0 while (q.isNotEmpty()) { val cube = q.removeFirst() if (cube in visited) continue visited.add(cube) directions.map { Triple( cube.first + it.first, cube.second + it.second, cube.third + it.third, ) }.forEach { next -> if (next.first in minX..maxX && next.second in minY..maxY && next.third in minZ..maxZ && next !in visited) { if (next in map) { out++ } else if (next !in map && next !in visited) { q.add(next) } } } } return out } val testInputA = readInput("Day18_test_a") val testInputB = readInput("Day18_test_b") check(part1(testInputA) == 10) check(part1(testInputB) == 64) check(part2(testInputB) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
2,540
aoc-2022
Apache License 2.0
src/main/kotlin/Day7.kt
ueneid
575,213,613
false
null
class Day7(inputs: List<String>) { private val root = parse(inputs).apply { calcSize() } enum class FileType(val type: String) { FILE("file"), DIR("DIR"), DUMMY("DUMMY") } private class FileTree(val type: FileType, val name: String, var size: Int, val children: MutableList<FileTree>) { constructor(type: Day7.FileType) : this(type, "", 0, mutableListOf()) constructor(type: Day7.FileType, name: String) : this(type, name, 0, mutableListOf()) constructor(type: Day7.FileType, name: String, size: Int) : this(type, name, size, mutableListOf()) fun calcSize(): Int { return when (type) { FileType.DIR, FileType.DUMMY -> { size = children.sumOf { it.calcSize() } size } FileType.FILE -> size } } } private fun parse(input: List<String>): FileTree { val fileTree = FileTree(FileType.DUMMY) val dirStack = ArrayDeque<FileTree>() dirStack.add(fileTree) var cur = fileTree input .asSequence() .map { it.split(" ") } .filterNot { it[0] == "dir" || it[1] == "ls" } .forEach { commands -> if (commands[0] == "$" && commands[1] == "cd") { if (commands[2] == "..") { dirStack.removeLast() } else { val d = FileTree(FileType.DIR, commands[2]) dirStack.last().children.add(d) dirStack.add(d) } cur = dirStack.last() } else if (commands[0].matches("""^\d+$""".toRegex())) { cur.children.add(FileTree(FileType.FILE, commands[1], commands[0].toInt())) } } return fileTree.children[0] } fun solve1(): Int { val q = ArrayDeque<FileTree>() val lessThan10000 = mutableListOf<FileTree>() q.add(root) while (q.isNotEmpty()) { val ft = q.removeFirst() if (ft.type == FileType.DIR) { if (ft.size < 100_000) { lessThan10000.add(ft) } ft.children.forEach { if (it.type == FileType.DIR) { q.add(it) } } } } return lessThan10000.sumOf { it.size } } fun solve2(): Int { val requiredUnusedSpace = 30_000_000 - (70_000_000 - root.size) val q = ArrayDeque<FileTree>() var candidate = FileTree(FileType.DUMMY, "dummy", 70_000_000) q.add(root) while (q.isNotEmpty()) { val ft = q.removeFirst() if (ft.type == FileType.DIR) { if (ft.size > requiredUnusedSpace && ft.size - requiredUnusedSpace < candidate.size - requiredUnusedSpace) { candidate = ft } ft.children.forEach { if (it.type == FileType.DIR) { q.add(it) } } } } return candidate.size } } fun main() { val obj = Day7(Resource.resourceAsListOfString("day7/input.txt")) println(obj.solve1()) println(obj.solve2()) }
0
Kotlin
0
0
743c0a7adadf2d4cae13a0e873a7df16ddd1577c
3,386
adventcode2022
MIT License
src/day3/Day03.kt
francoisadam
573,453,961
false
{"Kotlin": 20236}
package day3 import readInput fun main() { fun part1(input: List<String>): Int { return input.map { it.toRucksack() }.sumOf { it.findDuplicate().priority() } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { it.toElfGroup().findBadge().priority() } } // test if implementation meets criteria from the description, like: val testInput = readInput("day3/Day03_test") val testPart1 = part1(testInput) println("testPart1: $testPart1") val testPart2 = part2(testInput) println("testPart2: $testPart2") check(testPart1 == 157) check(testPart2 == 70) val input = readInput("day3/Day03") println("part1 : ${part1(input)}") println("part2 : ${part2(input)}") } private data class Rucksack( val firstCompartment: List<Char>, val secondCompartment: List<Char>, ) { fun findDuplicate(): Char = firstCompartment.first { secondCompartment.contains(it) } } private fun String.toRucksack(): Rucksack { val allItems = this.toCharArray().toList() return Rucksack( firstCompartment = allItems.subList(0, allItems.size / 2), secondCompartment = allItems.subList(allItems.size / 2, allItems.size), ) } private fun Char.priority(): Int = if (this.isLowerCase()) { this.code - 96 } else { this.code - 38 } private data class ElfGroup( val firstElf: List<Char>, val secondElf: List<Char>, val thirdElf: List<Char>, ) private fun List<String>.toElfGroup() = ElfGroup( firstElf = this.first().toCharArray().toList(), secondElf = this[1].toCharArray().toList(), thirdElf = this.last().toCharArray().toList(), ) private fun ElfGroup.findBadge(): Char { val possibleBadges = mutableListOf<Char>() possibleBadges.addAll(firstElf) possibleBadges.removeIf { !secondElf.contains(it) || !thirdElf.contains(it) } return possibleBadges.first() }
0
Kotlin
0
0
e400c2410db4a8343c056252e8c8a93ce19564e7
1,908
AdventOfCode2022
Apache License 2.0
src/Day17.kt
sabercon
648,989,596
false
null
fun main() { abstract class Point(val dimension: Int) { abstract fun neighbors(): List<Point> protected fun deltas(): List<List<Int>> { val seq = generateSequence(listOf(emptyList<Int>())) { deltas -> deltas.flatMap { delta -> (-1..1).map { delta + it } } } return seq.elementAt(dimension).filterNot { it.all { d -> d == 0 } } } } data class Point3D(val x: Int = 0, val y: Int = 0, val z: Int = 0) : Point(3) { override fun neighbors(): List<Point> { return deltas().map { (dx, dy, dz) -> Point3D(x + dx, y + dy, z + dz) } } } data class Point4D(val x: Int = 0, val y: Int = 0, val z: Int = 0, val w: Int = 0) : Point(4) { override fun neighbors(): List<Point> { return deltas().map { (dx, dy, dz, dw) -> Point4D(x + dx, y + dy, z + dz, w + dw) } } } fun process(points: Set<Point>): Set<Point> { return (points + points.flatMap { it.neighbors() }) .filter { point -> val activeNeighbors = point.neighbors().count { it in points } if (point in points) { activeNeighbors == 2 || activeNeighbors == 3 } else { activeNeighbors == 3 } } .toSet() } fun processSequence(points: Set<Point>): Sequence<Set<Point>> { return generateSequence(points) { process(it) } } val input = readLines("Day17") input.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == '#') Point3D(x, y) else null } } .let { processSequence(it.toSet()) } .elementAt(6) .size.println() input.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == '#') Point4D(x, y) else null } } .let { processSequence(it.toSet()) } .elementAt(6) .size.println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
1,939
advent-of-code-2020
MIT License
src/Day08.kt
raneric
573,109,642
false
{"Kotlin": 13043}
fun main() { fun part1(input: List<String>): Int { val listOfInt = input.convertToIntArray() return countVisibleTree(listOfInt) } fun part2(input: List<String>): Int { val listOfInt = input.convertToIntArray() return getHigherScore(listOfInt) } val input = readInput("Day08") println(part1(input)) println(part2(input)) } fun List<String>.convertToIntArray(): List<List<Int>> { val dataList = mutableListOf<List<Int>>() for (i in 0 until this.size) { dataList.add(this[i].map { it.digitToInt() }) } return dataList } //---------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------PART 01------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- fun countVisibleTree(list: List<List<Int>>): Int { var total = (list.size * 2) - 2 + (list[0].size * 2) - 2 for (i in 1 until list.lastIndex) { for (j in 1 until list[i].lastIndex) { if (checkInLine(list, i, j) || checkInColumn(list, i, j)) { total++ } } } return total } fun checkInLine(row: List<List<Int>>, i: Int, j: Int): Boolean { val left = row[i].subList(0, j).filter { it >= row[i][j] } val right = row[i].subList(j + 1, row.size).filter { it >= row[i][j] } return left.isEmpty() || right.isEmpty() } fun checkInColumn(list: List<List<Int>>, i: Int, j: Int): Boolean { val column = list.map { it[j] } val top = column.subList(0, i).filter { it >= list[i][j] } val bottom = column.subList(i + 1, list.size).filter { it >= list[i][j] } return top.isEmpty() || bottom.isEmpty() } //---------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------PART 2------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- fun getHigherScore(listOfInt: List<List<Int>>): Int { var higher = Int.MIN_VALUE var tempResult: Int for (i in 1 until listOfInt.lastIndex) { for (j in 1 until listOfInt[i].lastIndex) { tempResult = getHorizontalScore(listOfInt, i, j) * getVerticalScore(listOfInt, i, j) higher = higher.coerceAtLeast(tempResult) } } return higher } fun getHorizontalScore(row: List<List<Int>>, i: Int, j: Int): Int { val left = row[i].subList(0, j).reversed().countUntilHigher(row[i][j]) val right = row[i].subList(j + 1, row.size).countUntilHigher(row[i][j]) return left * right } fun getVerticalScore(data: List<List<Int>>, i: Int, j: Int): Int { val column = data.map { it[j] } val top = column.subList(0, i).reversed().countUntilHigher(data[i][j]) val bottom = column.subList(i + 1, column.size).countUntilHigher(data[i][j]) return top * bottom } private fun List<Int>.countUntilHigher(value: Int): Int { var count = 0 for (data in this) { if (data <= value) { count++ if (data == value) break } else { count++ break } } return count }
0
Kotlin
0
0
9558d561b67b5df77c725bba7e0b33652c802d41
3,423
aoc-kotlin-challenge
Apache License 2.0
src/Day18.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
import kotlin.math.max import kotlin.math.min data class Point3D(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Point3D) = Point3D(x + other.x, y + other.y, z + other.z) fun within(minPos: Point3D, maxPos: Point3D) = (x in minPos.x..maxPos.x) && (y in minPos.y..maxPos.y) && (z in minPos.z..maxPos.z) fun minimum(other: Point3D) = Point3D(min(x, other.x), min(y, other.y), min(z, other.z)) fun maximum(other: Point3D) = Point3D(max(x, other.x), max(y, other.y), max(z, other.z)) } // flood fill, collecting each point within the boundary fun flood(lava: Set<Point3D>, pos: Point3D, minPos: Point3D, maxPos: Point3D): Set<Point3D> { val water = mutableSetOf<Point3D>() val q = ArrayDeque<Point3D>().apply { addFirst(pos) } val outsideMin = minPos + Point3D(-1, -1, -1) val outsideMax = maxPos + Point3D(1, 1, 1) while (q.isNotEmpty()) { val curr = q.removeFirst() if (curr !in water) { water += curr listOf( Point3D(-1, 0, 0), Point3D(1, 0, 0), Point3D(0, -1, 0), Point3D(0, 1, 0), Point3D(0, 0, -1), Point3D(0, 0, 1) ).forEach { val n = curr + it if (n !in lava && n !in water && n.within(outsideMin, outsideMax)) { q.addFirst(n) } } } } return water } fun main() { fun part1(input: List<String>): Int { val droplets = input.map { val (x, y, z) = it.trim().split(",").map { p -> p.toInt() } Point3D(x, y, z) }.toSet() return droplets .flatMap { d -> listOf( Point3D(-1, 0, 0), Point3D(1, 0, 0), Point3D(0, -1, 0), Point3D(0, 1, 0), Point3D(0, 0, -1), Point3D(0, 0, 1) ).map { n -> n + d } }.count { it !in droplets } } fun part2(input: List<String>): Int { val droplets = input.map { val (x, y, z) = it.trim().split(",").map { p -> p.toInt() } Point3D(x, y, z) }.toSet() val minPos = droplets.fold( Point3D( Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE ) ) { acc, d -> acc.minimum(d) } + Point3D(-1, -1, -1) val maxPos = droplets.fold( Point3D( Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE ) ) { acc, d -> acc.maximum(d) } + Point3D(1, 1, 1) val water = flood(droplets, minPos, minPos, maxPos) // area without "air". Ones that can be filled with water return droplets .flatMap { d -> listOf( Point3D(-1, 0, 0), Point3D(1, 0, 0), Point3D(0, -1, 0), Point3D(0, 1, 0), Point3D(0, 0, -1), Point3D(0, 0, 1) ).map { n -> n + d } } .count { it !in droplets && it in water } } // sanity check val example = setOf(Point3D(1, 1, 1), Point3D(2, 1, 1)) // neighbors that are not part of the original set println(example.flatMap { e -> listOf( Point3D(-1, 0, 0), Point3D(1, 0, 0), Point3D(0, -1, 0), Point3D(0, 1, 0), Point3D(0, 0, -1), Point3D(0, 0, 1) ).map { n -> n + e } }.count { it !in example }) // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
4,013
advent-of-code-2022
Apache License 2.0
y2019/src/main/kotlin/adventofcode/y2019/Day10.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import adventofcode.util.vector.Vec2 import kotlin.math.absoluteValue fun main() = Day10.solve() object Day10 : AdventSolution(2019, 10, "Monitoring Station") { override fun solvePartOne(input: String) = losPerAsteroid(parseToAsteroids(input.lines())).values.maxOrNull() override fun solvePartTwo(input: String): Int { val asteroids = parseToAsteroids(input.lines()) val station = losPerAsteroid(asteroids).maxByOrNull { it.value }!!.key val vectorsToOtherAsteroids = asteroids .asSequence() .filter { it != station } .filter { lineOfSight(station, it, asteroids) } .map { it - station } .sortedBy { it.y.toDouble() / it.x.toDouble() } .sortedBy { it.x < 0 } .toList() val targetAsteroid = vectorsToOtherAsteroids[199] + station return targetAsteroid.x * 100 + targetAsteroid.y } private fun parseToAsteroids(grid: List<String>): Set<Vec2> = sequence { for (y in grid.indices) for (x in grid[0].indices) if (grid[y][x] == '#') yield(Vec2(x, y)) }.toSet() private fun losPerAsteroid(asteroids: Set<Vec2>) = asteroids.associateWith { k -> asteroids.filter { it != k }.count { other -> lineOfSight(k, other, asteroids) } } private fun lineOfSight(from: Vec2, to: Vec2, blockingPoints: Set<Vec2>): Boolean { val step = (from - to).reducedAngle() return generateSequence(from - step) { it - step } .takeWhile { it != to } .none { it in blockingPoints } } private fun Vec2.reducedAngle() = this / gcd(x.absoluteValue, y.absoluteValue) private tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,880
advent-of-code
MIT License
src/Day12.kt
rod41732
572,917,438
false
{"Kotlin": 85344}
import java.util.* fun main() { val input = readInput("Day12") val inputTest = readInput("Day12_test") fun part1(input: List<String>): Int { val mapRaw = input.map { it.toList() } val start = mapRaw.findIndex2D('S').first() val end = mapRaw.findIndex2D('E').first() val map = mapRaw.map { row -> row.map(::calculateHeight) } return bfsDistance(listOf(start), map, end) } fun part2(input: List<String>): Int { val mapRaw = input.map { it.toList() } val starts = mapRaw.findIndex2D { it == 'S' || it == 'a' }.toList() val end = mapRaw.findIndex2D('E').first() val map = mapRaw.map { row -> row.map(::calculateHeight) } return bfsDistance(starts, map, end) } println(part1(inputTest)) check(part1(inputTest) == 31) println(part2(inputTest)) check(part2(inputTest) == 29) println("Part 1") println(part1(input)) println("Part 2") println(part2(input)) } private fun calculateHeight(code: Char): Int { return when (code) { 'S' -> 0 'E' -> 25 else -> code - 'a' } } private fun Coord.adjacents(): List<Coord> { return listOf( first to second + 1, first + 1 to second, first - 1 to second, first to second - 1, ) } private fun <T> MutableList<MutableList<T>>.setAt(pos: Coord, v: T) { val (x, y) = pos this[x][y] = v } private fun <T> List<List<T>>.getAt(pos: Coord): T { val (x, y) = pos return this[x][y] } private fun bfsDistance(starts: List<Coord>, map: List<List<Int>>, end: Coord): Int { val height = map.size val width = map.first().size val dist = MutableList(map.size) { MutableList(map[0].size) { Int.MAX_VALUE } } starts.forEach { dist.setAt(it, 0) } val q: Queue<Coord> = LinkedList(starts) while (!q.isEmpty()) { val pos = q.remove() val currentDist = dist.getAt(pos) val currentHeight = map.getAt(pos) // println("at: $pos dist: $currentDist height: ${map.getAt(pos)}") if (pos == end) break pos.adjacents().forEach { nextPos -> if (!(0 until height).contains(nextPos.first)) return@forEach if (!(0 until width).contains(nextPos.second)) return@forEach // println("possible next $nextPos ${map.getAt(nextPos)}") if (map.getAt(nextPos) > currentHeight + 1) return@forEach // println("possible next $nextPos") if (dist.getAt(nextPos) == Int.MAX_VALUE) { dist.setAt(nextPos, currentDist + 1) q.add(nextPos) } } } return dist.getAt(end) } private fun <T> List<List<T>>.findIndex2D(elem: T): Sequence<Coord> = sequence { forEachIndexed { i, row -> row.forEachIndexed { j, value -> if (value == elem) yield(i to j) } } } private fun <T> List<List<T>>.findIndex2D(pred: (T) -> Boolean): Sequence<Coord> = sequence { forEachIndexed { i, row -> row.forEachIndexed { j, value -> if (pred(value)) yield(i to j) } } }
0
Kotlin
0
0
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
3,067
advent-of-code-kotlin-2022
Apache License 2.0
src/Day15.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
import kotlin.math.absoluteValue import kotlin.time.ExperimentalTime import kotlin.time.measureTime private data class Coord( val x: Long, val y: Long, ) { fun tuningFrequency() = (x * 4000000) + y } private data class Sensor( val x: Long, val y: Long, val maxDistance: Long, ) { operator fun contains(point: Coord): Boolean { return (point.x - x).absoluteValue + (point.y - y).absoluteValue <= maxDistance } fun pointsJustOutOfRange(maxCoordinate: Long): Sequence<Coord> = sequence { val coordRange = 0..maxCoordinate fun Sequence<Coord>.limits() = take(maxDistance.toInt()) .dropWhile { it.x !in coordRange || it.y !in coordRange } .takeWhile { it.x in coordRange && it.y in coordRange } yieldAll(generateSequence(seed = Coord(x = x + maxDistance + 1, y = y)) { Coord(x = it.x - 1, y = it.y + 1) }.limits()) yieldAll(generateSequence(seed = Coord(x = x, y = y + maxDistance + 1)) { Coord(x = it.x - 1, y = it.y - 1) }.limits()) yieldAll(generateSequence(seed = Coord(x = x - maxDistance - 1, y = y)) { Coord(x = it.x + 1, y = it.y - 1) }.limits()) yieldAll(generateSequence(seed = Coord(x = x, y = y - maxDistance - 1)) { Coord(x = it.x + 1, y = it.y + 1) }.limits()) } } fun main() { fun part1(input: List<String>, y: Long): Int { return input.map { it.split("=", ",", ":").mapNotNull(String::toLongOrNull) } .flatMap { (sx, sy, bx, by) -> val maxDistance = (sx - bx).absoluteValue + (sy - by).absoluteValue val yDistance = (y - sy).absoluteValue val maxXDistance = maxDistance - yDistance (sx - maxXDistance).rangeTo(sx + maxXDistance).filterNot { (it to y) == (bx to by) } }.toSet().size } fun part2(input: List<String>, maxCoordinate: Long): Long { val sensors = input.map { it.split("=", ",", ":").mapNotNull(String::toLongOrNull) } .map { (sx, sy, bx, by) -> Sensor(x = sx, y = sy, maxDistance = (sx - bx).absoluteValue + (sy - by).absoluteValue) } return sensors.asSequence().flatMap { it.pointsJustOutOfRange(maxCoordinate) } .first { point -> sensors.none { point in it } } .tuningFrequency() } // test if implementation meets criteria from the description, like: val testInput = readLines("Day15_test") check(part1(testInput, y = 10) == 26) check(part2(testInput, maxCoordinate = 20) == 56000011L) val input = readLines("Day15") with(part1(input, y = 2000000)) { check(this == 5511201) println(this) } with(part2(input, maxCoordinate = 4000000)) { check(this == 11318723411840) println(this) } }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
2,771
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/day21/Day21.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day21 // Syntax sugar private fun <N> Pair<N, N>.swap() = second to first private fun Pair<Long, Long>.max() = if (first > second) first else second private fun Pair<Long, Long>.addFirst(number: Long) = (first + number) to (second) private fun Pair<Long, Long>.timesEach(number: Long) = (first * number) to (second * number) private operator fun Pair<Long, Long>.plus(other: Pair<Long, Long>) = (first + other.first) to (second + other.second) data class GameState(val position: Int, val score: Int = 0) class GameRules(private val minScoreToWin: Int) { fun move(gameState: GameState, increment: Int): GameState { val newPosition = ((gameState.position - 1 + increment) % 10) + 1 return GameState(newPosition, gameState.score + newPosition) } fun hasWon(gameState: GameState): Boolean = gameState.score >= minScoreToWin } fun playDeterministicGame(initialPositionPlayer1: Int, initialPositionPlayer2: Int): Int { tailrec fun play( currentPlayer: GameState, otherPlayer: GameState, diceSeq: Sequence<Int>, diceRolledCount: Int, gameRules: GameRules ): Int { val p = gameRules.move(currentPlayer, diceSeq.take(3).sum()) return if (gameRules.hasWon(p)) otherPlayer.score * (diceRolledCount + 3) else play(otherPlayer, p, diceSeq.drop(3), diceRolledCount + 3, gameRules) } val deterministicDice = sequence { while (true) yieldAll(1..100) } return play(GameState(initialPositionPlayer1), GameState(initialPositionPlayer2), deterministicDice, 0, GameRules(1_000)) } fun countUniversesInWhichPlayerWins(initialPositionPlayer1: Int, initialPositionPlayer2: Int): Pair<Long, Long> { /* * Three dice with values 1, 2 and 3 generate the following 'universes' * - 1x sum = 3; 1x[1, 1, 1] * - 3x sum = 4; 3x[1, 1, 2] * - 6x sum = 5; 3x[1, 1, 3] + 3x[1, 2, 2] * - 7x sum = 6; 6x[1, 2, 3] + 1x[2, 2, 2] * - 6x sum = 7; 3x[2, 2, 3] + 3x[1, 3 ,3] * - 3x sum = 8; 3x[2, 3, 3] * - 1x sum = 9; 1x[3, 3, 3] */ fun incMultiplier(increment: Int): Long = when (increment) { 3, 9 -> 1 4, 8 -> 3 5, 7 -> 6 6 -> 7 else -> 0 } fun play(currentPlayer: GameState, otherPlayer: GameState, gameRules: GameRules): Pair<Long, Long> { var victoryCounter = 0L to 0L for (increment in 3..9) { val p = gameRules.move(currentPlayer, increment) if (gameRules.hasWon(p)) { victoryCounter = victoryCounter.addFirst(incMultiplier(increment)) } else { victoryCounter += play(otherPlayer, p, gameRules).swap().timesEach(incMultiplier(increment)) } } return victoryCounter } return play(GameState(initialPositionPlayer1), GameState(initialPositionPlayer2), GameRules(21)) } fun main() { // I'm not parsing such a small input :) // Starting point for player 1 is 2 // Starting point for player 2 is 5 println("Part one: ${playDeterministicGame(2, 5)}") println("Part two: ${countUniversesInWhichPlayerWins(2, 5).max()}") }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
2,971
advent-of-code-2021
MIT License
src/Day03.kt
copperwall
572,339,673
false
{"Kotlin": 7027}
val priorities = buildPriorities() fun main() { two() } // Each line is a knapsack // Each knapsack is a list of characters, // split evenly across two compartments // Find the only thing shared between the two compartments fun one() { val knapsacks = readInput("Day03") val priorities = knapsacks.map { getPriorityFromKnapsack(it) } val sum = priorities.sum() println(sum) } fun two() { val knapsacks = readInput("Day03") // Chunk into threes val groups = knapsacks.chunked(3) var sum = 0 for (group in groups) { val (one, two, three) = group.map { it.toSet() } val intersection = one.intersect(two).intersect(three) val intersectingStr = intersection.toList()[0] sum += priorities.getValue(intersectingStr) } println(sum) } // Map<char, int> fun buildPriorities(): Map<Char, Int> { val lowercaseRange = 'a'..'z' val uppercaseRange = 'A'..'Z' var i = 1 val priorities = mutableMapOf<Char, Int>() for (c in lowercaseRange + uppercaseRange) { priorities[c] = i i += 1 } return priorities } fun getPriorityFromKnapsack(knapsack: String): Int { // split into two compartments val mid = knapsack.length / 2 val first = knapsack.substring(0 until mid) val second = knapsack.substring(mid) val intersection = first.split("").intersect(second.split("")) val intersectingStr = intersection.toList()[1] println(intersectingStr) println(priorities.getValue(intersectingStr[0])) return priorities.getValue(intersectingStr[0]) }
0
Kotlin
0
1
f7b856952920ebd651bf78b0e15e9460524c39bb
1,591
advent-of-code-2022
Apache License 2.0
2021/src/day04/Day04.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day04 import readInput fun Array<IntArray>.markNumber(nb: Int) { for (i in 0 until size) { for (j in 0 until this[i].size) { if (this[i][j] == nb) { this[i][j] = -1 } } } } fun Array<IntArray>.isWinning() : Boolean { for (i in 0 until size) { if (isLineWinning(this[i])) { // Check line return true } // Build an array with the column val column = IntArray(size) for (j in 0 until size) { column[j] = this[j][i] } if (isLineWinning(column)) { // Check column return true } } return false } fun isLineWinning(line: IntArray) = line.filterNot{ it < 0 }.isEmpty() fun Array<IntArray>.sumOfUnmarkedNumber() : Int { var sum = 0 for (line in this) { for (nb in line) { if (nb > 0) { sum += nb } } } return sum } fun part1(lines: List<String>) : Int { val numbers = lines[0].split(",").map { it.toInt() } val boards = mutableListOf<Array<IntArray>>() // Building the boards lines.drop(1).filter { it.isNotEmpty() }.forEachIndexed { idx, line -> val boardIdx = idx / 5 val boardLine = idx % 5 if (boardLine == 0) { boards.add(Array<IntArray>(5) { IntArray(1) }) } boards[boardIdx][boardLine] = line.split(" ").map { it.toIntOrNull() }.filterNotNull().toIntArray() } // Going through the numbers to validate them numbers.forEach { drawn -> boards.forEach { board -> board.markNumber(drawn) if (board.isWinning()) { return drawn * board.sumOfUnmarkedNumber() } } } return -1 } fun part2(lines: List<String>) : Int { val numbers = lines[0].split(",").map { it.toInt() } val boards = mutableListOf<Array<IntArray>>() // Building the boards lines.drop(1).filter { it.isNotEmpty() }.forEachIndexed { idx, line -> val boardIdx = idx / 5 val boardLine = idx % 5 if (boardLine == 0) { boards.add(Array<IntArray>(5) { IntArray(1) }) } boards[boardIdx][boardLine] = line.split(" ").map { it.toIntOrNull() }.filterNotNull().toIntArray() } // Going through the numbers to validate them numbers.forEach { drawn -> for (i in boards.indices.reversed()) { val board = boards[i] board.markNumber(drawn) if (board.isWinning()) { if (boards.size == 1) { // last board return drawn * board.sumOfUnmarkedNumber() } else { // remove the board so we don't check if it's winning / mark the number on already won boards boards.removeAt(i) } } } } return -1 } fun main() { val testInput = readInput("day04/test") println("part1(testInput) => " + part1(testInput)) println("part2(testInput) => " + part2(testInput)) val input = readInput("day04/input") println("part1(input) => " + part1(input)) println("part1(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
3,216
advent-of-code
Apache License 2.0
src/Day02.kt
jorgecastrejon
573,097,701
false
{"Kotlin": 33669}
fun main() { fun part1(input: List<String>): Int = input.parse(calculateOwnPlay = { _, own -> own.asPlay() }) .sumOf { (opponent, your) -> your.vs(opponent).bonus + your.bonus } fun part2(input: List<String>): Int = input.parse(calculateOwnPlay = { opponent, own -> own.matchPlay(opponent) }) .sumOf { (opponent, your) -> your.vs(opponent).bonus + your.bonus } val input = readInput("Day02") println(part1(input)) println(part2(input)) } enum class Play { Rock, Paper, Scissors } val Play.bonus: Int get() = ordinal + 1 val Play.winnableOpponent: Play get() = when (this) { Play.Rock -> Play.Scissors Play.Paper -> Play.Rock Play.Scissors -> Play.Paper } enum class Result { Win, Loose, Draw } val Result.bonus: Int get() = when (this) { Result.Win -> 6 Result.Loose -> 0 Result.Draw -> 3 } fun String.asPlay(): Play = when (this) { "A", "X" -> Play.Rock "B", "Y" -> Play.Paper else -> Play.Scissors } fun String.matchPlay(opponent: Play): Play = when (asResult()) { Result.Win -> Play.values().first { it !in listOf(opponent, opponent.winnableOpponent) } Result.Loose -> opponent.winnableOpponent Result.Draw -> opponent } fun String.asResult(): Result = when (this) { "X" -> Result.Loose "Y" -> Result.Draw else -> Result.Win } fun List<String>.parse(calculateOwnPlay: (Play, String) -> Play) = map { round -> round.split(" ").run { first().asPlay().let { it to calculateOwnPlay(it, last()) } } } fun Play.vs(other: Play): Result = when { this == other -> Result.Draw this.winnableOpponent == other -> Result.Win else -> Result.Loose }
0
Kotlin
0
0
d83b6cea997bd18956141fa10e9188a82c138035
1,812
aoc-2022
Apache License 2.0
src/Day12.kt
stevennoto
573,247,572
false
{"Kotlin": 18058}
fun main() { // Each square/node has a label (S, E, or a level), level, id (for uniqueness), and links to reachable nodes data class Node(val label:Char, val id:Int) { val level = when (label) { 'S' -> 1; 'E' -> 26; else -> label - 'a' + 1 } val sources = mutableSetOf<Node>() // nodes that can reach this one val destinations = mutableSetOf<Node>() // nodes that this one can reach } // Check a path between 2 nodes, and if passable, connect them fun validatePath(source:Node?, destination:Node?) { if (source == null || destination == null) return if (destination.level <= source.level + 1) { source.destinations.add(destination) destination.sources.add(source) } } // Read input into a 2D node array, convert to a graph of nodes showing possible paths, return start and end nodes fun buildGraph(input: List<String>): Pair<Node, Node> { var id = 0 val inputArray = input.map { it.toCharArray().map { Node(it, id++) } }.toTypedArray() var start:Node = Node('S', -1) var end:Node = Node('E', -1) inputArray.forEachIndexed { i, row -> row.forEachIndexed { j, node -> if (node.label == 'S') start = node if (node.label == 'E') end = node validatePath(node, inputArray.getOrNull(i - 1)?.getOrNull(j)) validatePath(node, inputArray.getOrNull(i + 1)?.getOrNull(j)) validatePath(node, inputArray.getOrNull(i)?.getOrNull(j - 1)) validatePath(node, inputArray.getOrNull(i)?.getOrNull(j + 1)) } } return Pair(start, end) } fun part1(input: List<String>): Int { // Build graph and get start & end nodes val (start, end) = buildGraph(input) // Do a breadth-first search through nodes, counting steps from start to end val visited = mutableListOf<Node>() var neighbors = setOf(start) var steps = 0 while(neighbors.isNotEmpty()) { visited.addAll(neighbors) neighbors = neighbors.flatMap { it.destinations }.filter { !visited.contains(it) }.toSet() steps++ if (neighbors.contains(end)) return steps } return 0 } fun part2(input: List<String>): Int { // Build graph and get start & end nodes val (start, end) = buildGraph(input) // Do a breadth-first search through nodes, counting steps from end to first level 'a' val visited = mutableListOf<Node>() var neighbors = setOf(end) var steps = 0 while(neighbors.isNotEmpty()) { visited.addAll(neighbors) neighbors = neighbors.flatMap { it.sources }.filter { !visited.contains(it) }.toSet() steps++ if (neighbors.count { it.level == 1 } >= 1) return steps } return 0 } // read input val testInput = readInput("Day12_test") val input = readInput("Day12") // part 1 test and solution check(part1(testInput) == 31) println(part1(input)) // part 2 test and solution check(part2(testInput) == 29) println(part2(input)) }
0
Kotlin
0
0
42941fc84d50b75f9e3952bb40d17d4145a3036b
3,232
adventofcode2022
Apache License 2.0
src/Day15.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
import kotlin.math.abs import kotlin.math.max private val lineFormat = """Sensor at x=([\d\-]+), y=([\d\-]+): closest beacon is at x=([\d\-]+), y=([\d\-]+)""".toRegex() private fun distance(point1: Pair<Int, Int>, point2: Pair<Int, Int>): Int { return abs(point1.first - point2.first) + abs(point1.second - point2.second) } private fun sensors(input: List<String>): Map<Pair<Int, Int>, Pair<Int, Int>> { val sensors = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() for (line in input) { val matchResult = lineFormat.matchEntire(line) val coordinates = matchResult!!.groupValues.subList(1, matchResult.groupValues.size).map { it.toInt() } val sensor = Pair(coordinates[0], coordinates[1]) val beacon = Pair(coordinates[2], coordinates[3]) sensors[sensor] = beacon } return sensors } private fun combinedRanges( sensorToBeacons: Map<Pair<Int, Int>, Pair<Int, Int>>, targetRow: Int ): MutableList<IntRange> { val impossibleRanges = mutableListOf<IntRange>() for ((sensor, beacon) in sensorToBeacons) { val distance = distance(sensor, beacon) val targetRowFromSensor = abs(targetRow - sensor.second) if (targetRowFromSensor <= distance) { val halfRange = distance - targetRowFromSensor val impossibleRange = sensor.first - halfRange..sensor.first + halfRange impossibleRanges.add(impossibleRange) } else { // not in range } } impossibleRanges.sortBy { it.first } val combinedRanges = mutableListOf<IntRange>() var currentRange: IntRange? = null for (range in impossibleRanges) { if (currentRange == null) { currentRange = range } else { if (range.first <= currentRange.last) { currentRange = currentRange.first..max(currentRange.last, range.last) } else { combinedRanges.add(currentRange) currentRange = range } } } combinedRanges.add(currentRange!!) return combinedRanges } private fun part1(sensorToBeacons: Map<Pair<Int, Int>, Pair<Int, Int>>, targetRow: Int): Int { val combinedRanges = combinedRanges(sensorToBeacons, targetRow) return combinedRanges.sumOf { it.last - it.first + 1 } - sensorToBeacons.values.toSet().filter { it.second == targetRow }.size } private fun part2(sensorToBeacons: Map<Pair<Int, Int>, Pair<Int, Int>>, maxCoordinate: Int): Long { var uncoveredX = -1 var uncoveredY = -1 for (y in 0..maxCoordinate) { val combinedRanges = combinedRanges(sensorToBeacons, y) var isFullyCovered = false for (combinedRange in combinedRanges) { if (combinedRange.first <= 0 && combinedRange.last >= maxCoordinate) { isFullyCovered = true continue } } if (!isFullyCovered) { uncoveredY = y if (combinedRanges[0].first == 1) { uncoveredX = 0 } else { for ((i, combinedRange) in combinedRanges.withIndex()) { if (combinedRange.first <= 0 && combinedRange.last >= 0 && combinedRange.last < maxCoordinate) { uncoveredX = combinedRange.last + 1 assert(i + 1 == combinedRanges.size || combinedRanges[i + 1].first == uncoveredX + 1) break } } } break } } return uncoveredX * 4000000L + uncoveredY } fun main() { val input = readInput("Day15") val targetRow = 2000000 val maxCoordinate = 4000000 // val input = readInput("Test") // val targetRow = 10 // val maxCoordinate = 20 val sensors = sensors(input) println("Part 1: " + part1(sensors, targetRow)) println("Part 2: " + part2(sensors, maxCoordinate)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
3,939
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/tonnoz/adventofcode23/day7/Seven.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day7 import com.tonnoz.adventofcode23.utils.readInput object Seven { @JvmStatic fun main(args: Array<String>) { val input = "inputSeven.txt".readInput() problemOne(input) problemTwo(input) } private fun problemOne(input: List<String>){ val time = System.currentTimeMillis() input .map { it.toHand() } .sorted() .foldIndexed(0){ i, acc , curr-> acc + curr.bid * (i + 1) } .let { println("solution p1: $it") } println("Time p1: ${System.currentTimeMillis() - time} ms") } private fun problemTwo(input: List<String>){ val time = System.currentTimeMillis() input .map { it.toHand2() } .sorted() .foldIndexed(0){ i, acc , curr-> acc + curr.bid * (i + 1) } .let { println("solution p2: $it") } println("Time p2: ${System.currentTimeMillis() - time} ms") } private val cardsMap = listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2') private val cardsMap2 = listOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J') //index 12 is J(oker) private fun String.toHand(): Hand { val (cards, bid) = this.split(" ") val cardsInt = cards.map { cardsMap.indexOf(it) }.toIntArray() val cardsValues = cards.groupingBy { it }.eachCount().toList().sortedByDescending { it.second } val categoryStrength = when { cardsValues.size == 1 -> 7 cardsValues.size == 2 && cardsValues[0].second == 4 -> 6 cardsValues.size == 2 && cardsValues[0].second == 3 -> 5 cardsValues.size == 3 && cardsValues[0].second == 3 -> 4 cardsValues.size == 3 && cardsValues[0].second == 2 && cardsValues[1].second == 2 -> 3 cardsValues.size == 4 && cardsValues[0].second == 2 -> 2 else -> 1 } return Hand(cards, categoryStrength, bid.toShort(), cardsInt) } private fun String.toHand2(): Hand { val (cards, bid) = this.split(" ") val cardsInt = cards.map { cardsMap2.indexOf(it) } val categoryStrength = (0..< 12).maxOf { maybeJoker -> val cardsIntJokerized = cardsInt.map { if (it == 12) maybeJoker else it } val cardsMap = cardsIntJokerized.groupingBy { it }.eachCount().toList().sortedByDescending { it.second } when { cardsMap.size == 1 -> 7 cardsMap.size == 2 && cardsMap[0].second == 4 -> 6 cardsMap.size == 2 && cardsMap[0].second == 3 -> 5 cardsMap.size == 3 && cardsMap[0].second == 3 -> 4 cardsMap.size == 3 && cardsMap[0].second == 2 && cardsMap[1].second == 2 -> 3 cardsMap.size == 4 && cardsMap[0].second == 2 -> 2 else -> 1 } } return Hand(cards, categoryStrength, bid.toShort(), cardsInt.toIntArray()) } //I left cards here for debug purposes, but it can be removed private class Hand(val cards:String, val categoryStrength: Int, val bid: Short, val intValues : IntArray): Comparable<Hand> { override fun compareTo(other: Hand): Int { if (categoryStrength < other.categoryStrength) return -1 if (categoryStrength > other.categoryStrength) return 1 for (i in intValues.indices) { if (intValues[i] < other.intValues[i]) return 1 if (intValues[i] > other.intValues[i]) return -1 } return 0 } } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
3,271
adventofcode23
MIT License
src/Day16.kt
maewCP
579,203,172
false
{"Kotlin": 59412}
import kotlin.random.Random fun main() { val verbose = false val nodes = mutableMapOf<String, Day16Node>() var usableNodes = mutableListOf<Day16Node>() val map = mutableMapOf<Day16Node, List<Day16Node>>() val distances = mutableMapOf<Set<Day16Node>, Int>() val shortestPath = mutableMapOf<Day16Node, Int>() val queue = mutableListOf<Day16ShortestPath>() lateinit var goal: Day16Node fun printSteps1(valveSteps: MutableList<Day16Node>) { val prev = nodes["AA"]!! print("${prev.name}(${prev.rate})") (0 until valveSteps.size).forEach { i -> print(" -> ${distances[setOf(prev, valveSteps[i])]} -> ") print("${valveSteps[i].name}(${valveSteps[i].rate})") } println("") } fun printSteps2(valveSteps: MutableList<Day16Node>) { printSteps1(valveSteps.subList(0, valveSteps.size / 2)) printSteps1(valveSteps.subList(valveSteps.size / 2, valveSteps.size)) } fun calcScore1(valveSteps: MutableList<Day16Node>, minutes: Int): Int { var endOfMin = 0 var score = 0 var rate = 0 var curr = nodes["AA"] run breakForEach@{ valveSteps.forEach { node -> var minPassed = distances[setOf(curr, node)]!! + 1 if (endOfMin + minPassed > minutes) minPassed = minutes - endOfMin score += minPassed * rate rate += node.rate endOfMin += minPassed curr = node if (endOfMin >= minutes) return@breakForEach } } if (endOfMin < minutes) { score += (minutes - endOfMin) * rate } return score } fun calcScore2(valveSteps: MutableList<Day16Node>, minutes: Int): Int { return calcScore1(valveSteps.subList(0, valveSteps.size / 2), minutes) + calcScore1(valveSteps.subList(valveSteps.size / 2, valveSteps.size), minutes) } fun tryNext(shortestPathSolution: Day16ShortestPath, next: Day16Node) { if (next in shortestPathSolution.path) return val newPath = shortestPathSolution.path.toMutableList() newPath.add(next) queue.add(Day16ShortestPath(newPath)) } fun search() { val solution = queue.removeAt(0) val curr = solution.path[solution.path.size - 1] val bSolution = shortestPath[curr] if (bSolution == null) shortestPath[curr] = solution.path.size else if (solution.path.size < shortestPath[curr]!!) shortestPath[curr] = solution.path.size else return if (curr == goal) return map[curr]!!.forEach { next -> tryNext(solution, next) } } fun prepareInput(input: List<String>) { nodes.clear() usableNodes.clear() map.clear() distances.clear() val regex = "Valve (.+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)".toRegex() input.forEach { line -> val groups = regex.find(line)!!.destructured.toList() nodes[groups[0]] = Day16Node(groups[0], groups[1].toInt()) } input.forEach { line -> val groups = regex.find(line)!!.destructured.toList() val node = nodes[groups[0]]!! val connections = groups[2].split(", ").map { nodes[it]!! } map[node] = connections } if (verbose) println("Node size: ${nodes.size}") usableNodes = nodes.values.filter { node -> node.rate > 0 || node.name == "AA" }.toMutableList() usableNodes.forEach { node -> usableNodes.filter { it != node }.forEach { targetNode -> shortestPath.clear() queue.clear() queue.add(Day16ShortestPath(mutableListOf(node))) goal = targetNode do { search() } while (queue.size > 0) distances[setOf(node, targetNode)] = shortestPath[targetNode]!! - 1 } } usableNodes.remove(nodes["AA"]) if (verbose) println("Usable Node Size: ${usableNodes.size}") } fun part1(input: List<String>): Int { prepareInput(input) usableNodes.shuffled() var global = usableNodes.toMutableList() (1..30).forEach { i -> var local = usableNodes.shuffled().toMutableList() var noBetter = 0 while (noBetter <= 100000) { val trySteps = local.toMutableList() val nodeIdx = Random.nextInt(0, usableNodes.size - 1) val insertIntoIdx = Random.nextInt(0, usableNodes.size - 2) val node = trySteps.removeAt(nodeIdx) trySteps.add(insertIntoIdx, node) if (calcScore1(local, 30) < calcScore1(trySteps, 30)) local = trySteps else noBetter++ } if (verbose) println("***************************") if (verbose) printSteps1(local) if (verbose) println("Local score $i = ${calcScore1(local, 30)}") if (calcScore1(local, 30) > calcScore1(global, 30)) global = local } if (verbose) println("***************************") if (verbose) printSteps1(global) if (verbose) println("Global score: ${calcScore1(global, 30)}") return calcScore1(global, 30) } fun part2(input: List<String>): Int { prepareInput(input) usableNodes.shuffled() var global = usableNodes.toMutableList() (1..30).forEach { i -> var local = usableNodes.shuffled().toMutableList() var noBetter = 0 while (noBetter <= 1000000) { val trySteps = local.toMutableList() val nodeIdx = Random.nextInt(0, usableNodes.size - 1) val insertIntoIdx = Random.nextInt(0, usableNodes.size - 2) val node = trySteps.removeAt(nodeIdx) trySteps.add(insertIntoIdx, node) if (calcScore2(local, 26) < calcScore2(trySteps, 26)) local = trySteps else noBetter++ } if (verbose) println("***************************") if (verbose) printSteps2(local) if (verbose) println("Local score $i = ${calcScore2(local, 26)}") if (calcScore2(local, 26) > calcScore2(global, 26)) global = local } if (verbose) println("***************************") if (verbose) printSteps2(global) if (verbose) println("Global score: ${calcScore2(global, 26)}") return calcScore2(global, 26) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day16_test") check(part1(testInput) == 1651) check(part2(testInput) == 1707) val input = readInput("Day16") part1(input).println() part2(input).println() } data class Day16Node(val name: String, val rate: Int) data class Day16ShortestPath(val path: MutableList<Day16Node>)
0
Kotlin
0
0
8924a6d913e2c15876c52acd2e1dc986cd162693
7,027
advent-of-code-2022-kotlin
Apache License 2.0
src/Day09.kt
valerakostin
574,165,845
false
{"Kotlin": 21086}
import kotlin.math.abs data class Loc(val x: Int, val y: Int) { fun adjust(tail: Loc): Loc { val diffX = x - tail.x val diffY = y - tail.y if ((abs(diffX) == 1 && diffY == 0) || (diffX == 0 && abs(diffY) == 1) || (diffX == 0 && diffY == 0) || (abs(diffX) == 1 && abs(diffY) == 1) ) return tail if (abs(diffX) == 2 && diffY == 0) { return if (diffX > 0) Loc(tail.x + 1, tail.y) else Loc(tail.x - 1, tail.y) } else if (abs(diffY) == 2 && diffX == 0) { return if (diffY > 0) Loc(tail.x, tail.y + 1) else Loc(tail.x, tail.y - 1) } else { // diagonal if (diffX == 2 && diffY == 1 || diffX == 1 && diffY == 2 || diffX == 2 && diffY == 2) return Loc(tail.x + 1, tail.y + 1) else if (diffX == -2 && diffY == 1 || diffX == -1 && diffY == 2 || diffX == -2 && diffY == 2) return Loc(tail.x - 1, tail.y + 1) else if (diffX == 1 && diffY == -2 || diffX == 2 && diffY == -1 || diffX == 2 && diffY == -2) return Loc(tail.x + 1, tail.y - 1) else if (diffX == -2 && diffY == -1 || diffX == -1 && diffY == -2 || diffX == -2 && diffY == -2) return Loc(tail.x - 1, tail.y - 1) } return tail } } fun main() { fun computeTailPosition(input: List<String>, components: List<Loc>): Int { val visited = mutableSetOf<Loc>() val items = mutableListOf<Loc>() items.addAll(components) for (move in input) { val (dir, step) = move.split(" ") val diff = when (dir) { "R" -> Loc(1, 0) "L" -> Loc(-1, 0) "U" -> Loc(0, 1) else -> Loc(0, -1) } repeat(step.toInt()) { val tmp = mutableListOf<Loc>() var head = items[0] head = Loc(head.x + diff.x, head.y + diff.y) tmp.add(head) for (t in 1 until items.size) { val next = tmp.last().adjust(items[t]) tmp.add(next) } items.clear() items.addAll(tmp) visited.add(items.last()) } } return visited.size } fun part1(input: List<String>): Int { return computeTailPosition(input, listOf(Loc(0, 0), Loc(0, 0))) } fun part2(input: List<String>): Int { val items = mutableListOf<Loc>() repeat(10) { items.add(Loc(0, 0)) } return computeTailPosition(input, items) } val testInput = readInput("Day09_test") check(part1(testInput) == 13) val input = readInput("Day09") println(part1(input)) check(part2(testInput) == 1) check(part2(listOf("R 5", "U 8", "L 8", "D 3", "R 17", "D 10", "L 25", "U 20")) == 36) println(part2(input)) }
0
Kotlin
0
0
e5f13dae0d2fa1aef14dc71c7ba7c898c1d1a5d1
3,059
AdventOfCode-2022
Apache License 2.0
day18/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
import java.io.File fun main() { val input = readInputFile() println("Part I: the solution is ${solvePartI(input, 10)}.") /* Determined by inspection that after 1000 iterations (probably sooner), the process repeats itself with a period of 28 iterations. (1000000000 - 1000) % 28 = 0, so the solution for 1000000000 is the same as the solution for 1000 */ println("Part II: the solution is ${solvePartI(input, 1000)}.") } fun readInputFile(): List<String> { return File(ClassLoader.getSystemResource("input.txt").file).readLines() } fun solvePartI(inputLumberArea: List<String>, numberOfIterations: Int): Int { val height = inputLumberArea.size val width = inputLumberArea[0].length var lumberArea = inputLumberArea for (i in 1..numberOfIterations) { val newLumberArea = lumberArea.toMutableList() for (x in 0 until width) { for (y in 0 until height) { val adjacentCoordinates = getAdjacentCoordinates(Coordinate(x, y), height, width) val adjacentAcres = adjacentCoordinates.map { lumberArea[it.y][it.x] } if (lumberArea[y][x] == '.' && adjacentAcres.filter { it == '|' }.size >= 3) { newLumberArea[y] = newLumberArea[y].replaceRange(x, x + 1, "|") } else if (lumberArea[y][x] == '|' && adjacentAcres.filter { it == '#' }.size >= 3) { newLumberArea[y] = newLumberArea[y].replaceRange(x, x + 1, "#") } else if (lumberArea[y][x] == '#' && (adjacentAcres.none { it == '#' } || adjacentAcres.none { it == '|' })) { newLumberArea[y] = newLumberArea[y].replaceRange(x, x + 1, ".") } } } lumberArea = newLumberArea } val numberOfWoodedAcres = lumberArea .flatMap { it -> it.toList() } .filter { it == '|' } .size val numberOfLumberyards = lumberArea .flatMap { it -> it.toList() } .filter { it == '#' } .size return numberOfWoodedAcres * numberOfLumberyards } fun getAdjacentCoordinates(coordinate: Coordinate, height: Int, width: Int): List<Coordinate> { val result = mutableListOf<Coordinate>() for (x in (coordinate.x - 1)..(coordinate.x + 1)) { for (y in (coordinate.y - 1)..(coordinate.y + 1)) { val potentialAdjacentCoordinate = Coordinate(x, y) if (x in (0 until width) && y in (0 until height) && potentialAdjacentCoordinate != coordinate) { result.add(potentialAdjacentCoordinate) } } } return result } data class Coordinate(val x: Int, val y: Int)
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
2,751
AdventOfCode2018
MIT License
src/Day24.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
fun main() { Day24.printSolutionIfTest(18, 54) } object Day24 : Day<Int, Int>(24) { override fun part1(lines: List<String>): Int { val map = parseMap(lines) return solve(map, map.entryPoint(), map.exitPoint()) } override fun part2(lines: List<String>): Int { val map = parseMap(lines) return solve(map, map.entryPoint(), map.exitPoint(), map.entryPoint(), map.exitPoint()) } private fun List<List<String>>.entryPoint() = Point(this[0].indexOfFirst { it == "." }, 0) private fun List<List<String>>.exitPoint() = Point(this[this.lastIndex].indexOfFirst { it == "." }, this.lastIndex) private val List<List<String>>.maxx: Int get() = this[0].lastIndex private val List<List<String>>.maxy: Int get() = lastIndex private fun solve(startMap: List<List<String>>, vararg route: Point): Int { var total = 0 var map = startMap route.asList().windowed(2, 1).forEach { val (out, nextMap) = calculate(map, it[0], it[1]) map = nextMap total += out } return total } private fun calculate(startMap: List<List<String>>, entryPoint: Point, exitPoint: Point): Pair<Int, List<List<String>>> { var possiblePositions = listOf(entryPoint) var map = startMap var count = 0 while (!possiblePositions.contains(exitPoint)) { map = cycle(map) possiblePositions = checkPositions(map, possiblePositions).distinct() count++ } return Pair(count, map) } private fun checkPositions(map: List<List<String>>, positions: List<Point>) = positions.flatMap { adjacentPoints(it, map.maxx, map.maxy).filter { newPos -> map[newPos.y][newPos.x] == "." } } private fun adjacentPoints(pos: Point, maxx: Int, maxy: Int) = listOfNotNull( pos, if (pos.x > 0) Point(pos.x - 1, pos.y) else null, if (pos.y > 0) Point(pos.x, pos.y - 1) else null, if (pos.x < maxx) Point(pos.x + 1, pos.y) else null, if (pos.y < maxy) Point(pos.x, pos.y + 1) else null ) private fun cycle(map: List<List<String>>): List<List<String>> { val maxx = map.maxx val maxy = map.maxy val result = map.map { row -> row.map { if (it == "#") "#" else "." }.toMutableList() }.toMutableList() map.forEachIndexed { y, row -> row.forEachIndexed { x, cell -> cell.chunked(1).forEach { when (it) { ">" -> setCell(maxx, maxy, x + 1, y, result, it) "<" -> setCell(maxx, maxy, x - 1, y, result, it) "^" -> setCell(maxx, maxy, x, y - 1, result, it) "v" -> setCell(maxx, maxy, x, y + 1, result, it) } } } } return result } private fun setCell(maxx: Int, maxy: Int, x: Int, y: Int, result: MutableList<MutableList<String>>, s: String) { val newx = when (x) { 0 -> maxx-1; maxx -> 1 else -> x} val newy = when (y) { 0 -> maxy-1; maxy -> 1 else -> y} result[newy][newx] += s } data class Point(val x: Int, val y: Int) private fun parseMap(lines: List<String>) = lines.map { l -> l.chunked(1) } }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
3,312
advent-of-code-2022
Apache License 2.0
src/Day02.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
private enum class Shape(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3) } private enum class Outcome(val score: Int) { WIN(6), DRAW(3), LOSE(0) } private val Char.shape: Shape get() = when (this) { 'A', 'X' -> Shape.ROCK 'B', 'Y' -> Shape.PAPER 'C', 'Z' -> Shape.SCISSORS else -> error("AX BY CZ") } private val Char.outcome: Outcome get() = when (this) { 'X' -> Outcome.LOSE 'Y' -> Outcome.DRAW 'Z' -> Outcome.WIN else -> error("XYZ") } private fun win(t: Shape): Shape { return when (t) { Shape.ROCK -> Shape.PAPER Shape.PAPER -> Shape.SCISSORS else -> Shape.ROCK } } private fun outcome(my: Shape, other: Shape): Outcome { return when (my) { other -> Outcome.DRAW win(other) -> Outcome.WIN else -> Outcome.LOSE } } private fun applyOutcomeFor(outcome: Outcome, opponent: Shape): Shape = when (outcome) { Outcome.DRAW -> opponent Outcome.WIN -> win(opponent) Outcome.LOSE -> win(win(opponent)) } fun main() { fun part1(input: List<String>): Int = input.map { line -> Pair(line[0].shape, line[2].shape) } .sumOf { (opponent, me) -> me.score + outcome(me, opponent).score } fun part2(input: List<String>): Int = input.map { line -> Pair(line[0].shape, line[2].outcome) } .sumOf { (opponent, outcome) -> outcome.score + applyOutcomeFor(outcome, opponent).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
0
8218c60c141ea2d39984792fddd1e98d5775b418
1,737
advent-of-kotlin-2022
Apache License 2.0
src/day01/Day01.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day01 import readInput fun main() { fun topCaloriesElf(input: List<String>): ElfWithCalories { return getElfsWithSumCalories(input) .maxBy { (_, sumCalories) -> sumCalories } } fun topThreeCalories(input: List<String>): Int { return getElfsWithSumCalories(input) .toList() .sortedByDescending { (_, sumCalories) -> sumCalories } .take(3) .sumOf { it.sumCalories } } // test if implementation meets criteria from the description, like: val testInput = readInput("/day01/Day01_test") val part1Test = topCaloriesElf(testInput) check(part1Test.elfId == 4) check(part1Test.sumCalories == 24000) val topThreeCaloriesTest = topThreeCalories(testInput) println("topThreeCaloriesTest: $topThreeCaloriesTest") check(topThreeCaloriesTest == 45000) val input = readInput("/day01/Day01") println(topCaloriesElf(input)) println(topThreeCalories(input)) } fun getElfsWithSumCalories(input: List<String>): List<ElfWithCalories> = groupCaloriesByElf(input).map { it.first to it.second.sum() } .map { ElfWithCalories(it.first + 1, it.second) } fun groupCaloriesByElf(input: List<String>): List<Pair<Int, List<Int>>> = input.withPrefixSum { it == "" } .filter { it.second.isNotBlank() } .groupBy({ it.first }) { it.second.toInt() } .map { (elfId, calories) -> elfId to calories } data class ElfWithCalories(val elfId: Int, val sumCalories: Int) fun <T> List<T>.withPrefixSum(predicate: (T) -> Boolean): List<Pair<Int, T>> = prefixSum(predicate).zip(this) fun <T> List<T>.prefixSum(predicate: (T) -> Boolean): List<Int> = runningFold(0) { count, element -> count + if (predicate(element)) 1 else 0 }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
1,764
advent-of-code-22-kotlin
Apache License 2.0
y2020/src/main/kotlin/adventofcode/y2020/Day20.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution import adventofcode.util.vector.Vec2 fun main() = Day20.solve() object Day20 : AdventSolution(2020, 20, "Jurassic Jigsaw") { override fun solvePartOne(input: String) = unmatchedEdgeCounts(parseInput(input)) .filter { it.value == 2 } .keys .reduce(Long::times) override fun solvePartTwo(input: String): Int { val tiles: List<Tile> = parseInput(input) val unmatchedEdges = unmatchedEdgeCounts(tiles) val tilesByEdgecount: List<Map<Long, Tile>> = tiles.groupBy { unmatchedEdges[it.id] ?: 0 }.toSortedMap().values.map { it.associateBy { it.id } } val arrangedTiles = arrangePuzzle(listOf(), Vec2.origin, tilesByEdgecount)!! val image = cutTiles(arrangedTiles) val monster = Image( listOf( " # ", "# ## ## ###", " # # # # # # " ) ) val monsterCount = image.allOrientations().map { countMonsters(it, monster) }.first { it > 0 } fun Image.count() = grid.joinToString().count { it == '#' } return image.count() - monsterCount * monster.count() } private fun countMonsters(image: Image, monster: Image): Int { fun matches(slice: List<String>, monster: List<String>): Boolean { for (y in monster.indices) { for (x in monster[0].indices) { if (monster[y][x] != '#') continue if (slice[y][x] != '#') return false } } return true } return image.sequenceOfSlices(monster.grid[0].length, monster.grid.size) .count { matches(it.grid, monster.grid) } } private fun arrangePuzzle( grid: List<List<Tile>>, p: Vec2, tilesByEdgecount: List<Map<Long, Tile>> ): List<List<Tile>>? { if (p.y == 12) return grid val edges = listOf(p.x == 0, p.x == 11, p.y == 0, p.y == 11).count { it } fun isValidPlacement(tile: Tile): Boolean = when { p.x > 0 && grid[p.y][p.x - 1].right != tile.left -> false p.y > 0 && grid[p.y - 1][p.x].bottom != tile.top -> false else -> true } fun placeTile(tile: Tile): List<List<Tile>> = if (p.x == 0) grid.plusElement(listOf(tile)) else grid.dropLast(1).plusElement(grid.last() + tile) fun nextPosition() = if (p.x < 11) p.copy(x = p.x + 1) else p.copy(y = p.y + 1, x = 0) fun updateRemainingTiles(tile: Tile) = tilesByEdgecount.toMutableList().apply { this[edges] = this[edges].minus(tile.id) } return tilesByEdgecount[edges].values.asSequence() .flatMap(Tile::allOrientations) .filter(::isValidPlacement) .mapNotNull { tile -> arrangePuzzle(placeTile(tile), nextPosition(), updateRemainingTiles(tile)) } .firstOrNull() } private fun cutTiles(arrangedTiles: List<List<Tile>>): Image = arrangedTiles .map { line -> line.map { it.img.cropped(1, 1, it.img.width - 2, it.img.height - 2) } } .map { Image.stitchHorizontal(it) } .let { Image.stitchVertical(it) } private fun unmatchedEdgeCounts(tiles: List<Tile>): Map<Long, Int> = tiles .flatMap { t -> t.allEdges.map { it to t } } .groupBy({ it.first }, { it.second }) .values .mapNotNull { it.singleOrNull() } .groupingBy { it.id } .eachCount() .mapValues { it.value / 2 } private fun parseInput(input: String): List<Tile> = input.split("\n\n") .map { it.lines() } .map { Tile(it[0].drop(5).dropLast(1).toLong(), Image(it.drop(1))) } } private data class Tile(val id: Long, val img: Image) { val top = img.grid.first() val right = img.column(img.width - 1) val bottom = img.grid.last() val left = img.column(0) val allOrientations by lazy { img.allOrientations().map { Tile(id, it) } } val allEdges by lazy { listOf(top, right, bottom, left).let { it + it.map(String::reversed) } } } private data class Image(val grid: List<String>) { val width = grid[0].length val height = grid.size fun flipped() = grid.map(String::reversed).let(::Image) fun rotated() = grid[0].indices.reversed().map(this::column).let(::Image) fun cropped(x: Int, y: Int, width: Int, height: Int) = grid .slice(y until y + height) .map { line -> line.slice(x until x + width) } .let(::Image) fun column(x: Int) = grid.map { it[x] }.toCharArray().let(::String) fun allOrientations(): List<Image> = generateSequence(this, Image::rotated).take(4).toList().let { it.map(Image::flipped) + it } fun sequenceOfSlices(width: Int, height: Int) = sequence { for (y in 0 until grid.size - height) for (x in 0 until grid[0].length - width) yield(cropped(x, y, width, height)) } companion object { fun stitchHorizontal(images: List<Image>) = Image(images.first().grid.indices.map { y -> images.joinToString("") { it.grid[y] } }) fun stitchVertical(images: List<Image>) = Image(images.flatMap(Image::grid)) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
5,368
advent-of-code
MIT License
2015/Day13/src/main/kotlin/Main.kt
mcrispim
658,165,735
false
null
import java.io.File import java.util.* fun generateSequence(A: List<String>): Sequence<List<String>> { return sequence { val n = A.size val c = IntArray(n) val list = A.toMutableList() yield(list.toList()) var i = 0; while (i < n) { if (c[i] < i) { if (i % 2 == 0) { Collections.swap(list, 0, i) } else { Collections.swap(list, c[i], i) } yield(list) c[i] += 1 i = 0 } else { c[i] = 0 i += 1 } } } } fun addHostToPrefsAndPeople() { for (p in people) { prefs[Pair(p, "Host")] = 0 prefs[Pair("Host", p)] = 0 } people.add("Host") } fun mountPrefsAndPeople(input: List<String>) { val everybody = mutableSetOf<String>() prefs.clear() input.forEach { val parts = it.split(" ") val name1 = parts[0] val name2 = parts[10].dropLast(1) val value = if (parts[2] == "gain") parts[3].toInt() else -(parts[3].toInt()) prefs[Pair(name1, name2)] = value everybody.add(name1) everybody.add(name2) } people = everybody.toMutableList() } fun happyness(people: List<String>): Int { var happyness = 0 happyness += prefs[Pair(people.last(), people.first())]!! happyness += prefs[Pair(people.first(), people.last())]!! for ((personA, personB) in people.zipWithNext()) { happyness += prefs[Pair(personA, personB)]!! happyness += prefs[Pair(personB, personA)]!! } return happyness } fun calculateHappyness(table: Sequence<List<String>>): Int { var happyness = 0 table.forEachIndexed { index, people -> val normalizedPeople = normalizePeople(people) if (combinations.containsKey(normalizedPeople)) { return@forEachIndexed } val thisHappyness = happyness(normalizedPeople) combinations[normalizedPeople] = thisHappyness if (thisHappyness > happyness) { happyness = thisHappyness } } return happyness } fun normalizePeople(peopleAtTable: List<String>): List<String> { val firstPerson = people.first() val firstIndex = peopleAtTable.indexOf(firstPerson) val result = peopleAtTable.subList(firstIndex, peopleAtTable.size) + peopleAtTable.subList(0, firstIndex) return result } val prefs = mutableMapOf<Pair<String, String>, Int>() var people = mutableListOf<String>() val combinations = mutableMapOf<List<String>, Int>() fun main() { fun findMostHappynnes(): Int { val table: Sequence<List<String>> = generateSequence(people) return calculateHappyness(table) } val testInput = readInput("Day13_test") mountPrefsAndPeople(testInput) // printPrefsAndPeople() var part1Result = findMostHappynnes() check(part1Result == 330) val input = readInput("Day13_data") mountPrefsAndPeople(input) part1Result = findMostHappynnes() println("Part 1 answer: $part1Result") addHostToPrefsAndPeople() val part2Result2 = findMostHappynnes() println("Part 2 answer: $part2Result2") } /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines()
0
Kotlin
0
0
2f4be35e78a8a56fd1e078858f4965886dfcd7fd
3,414
AdventOfCode
MIT License
src/day8/Day08.kt
HGilman
572,891,570
false
{"Kotlin": 109639, "C++": 5375, "Python": 400}
package day8 import readInput fun main() { val testInput = readInput("day8/Day08_test") val testField = parseInput(testInput) check(part1(testField) == 21) check(part2(testField) == 8) val input = readInput("day8/Day08") val field = parseInput(input) println(part1(field)) println(part2(field)) } fun parseInput(input: List<String>) = input.map { it.map { c -> c.digitToInt() } } fun part1(field: List<List<Int>>): Int { val width = field.first().size val height = field.size var count = 0 for (y in 0 until height) { for (x in 0 until width) { val h = field[y][x] if (((y == 0 || y == height - 1 || x == 0 || x == width - 1)) // left || (0 until x).all { field[y][it] < h } // right || (x + 1 until width).all { field[y][it] < h } // top || (0 until y).all { field[it][x] < h } // bottom || (y + 1 until height).all { field[it][x] < h } ) { count++ } } } return count } fun part2(field: List<List<Int>>): Int { val width = field.first().size val height = field.size val distances = mutableListOf<Int>() for (y in 0 until height) { for (x in 0 until width) { if (y == 0 || y == height - 1 || x == 0 || x == width - 1) { continue } val h = field[y][x] val leftPart = (x - 1 downTo 0).map { field[y][it] } val left = leftPart.indexOfFirst { it >= h } val l = if (left == -1) leftPart.size else left + 1 val rightPart = (x + 1 until width).map { field[y][it] } val right = rightPart.indexOfFirst { it >= h } val r = if (right == -1) rightPart.size else right + 1 val topPart = (y - 1 downTo 0).map { field[it][x] } val top = topPart.indexOfFirst { it >= h } val t = if (top == -1) topPart.size else top + 1 val bottomPart = (y + 1 until height).map { field[it][x] } val bottom = bottomPart.indexOfFirst { it >= h } val b = if (bottom == -1) bottomPart.size else bottom + 1 distances.add(l * r * t * b) } } return distances.max() }
0
Kotlin
0
1
d05a53f84cb74bbb6136f9baf3711af16004ed12
2,361
advent-of-code-2022
Apache License 2.0
src/main/kotlin/io/pg/advent/day6/Main.kt
pgdejardin
159,992,959
false
null
package io.pg.advent.day6 import arrow.core.Some import arrow.instances.list.foldable.exists import arrow.syntax.collections.firstOption import io.pg.advent.utils.FileUtil import kotlin.math.absoluteValue fun main() { val lines = FileUtil.loadFile("/day6.txt") val sizePartOne = day6Part1(lines) println("What is the size of the largest area that isn't infinite?") println("It is $sizePartOne") println("---------------------------------------------------------") val sizePartTwo = day6Part2(lines) println("What is the size of the region containing all locations which have a total distance to all given coordinates of less than 10000?") println("It is $sizePartTwo") } data class Coordinate( val id: Int, val x: Int, val y: Int, val nearest: Int = id, val atEdge: Boolean = false, val total: Int = 0 ) fun parseInput(lines: List<String>) = lines.mapIndexed { index, s -> val coord = s.split(",").map { it.trim() } Coordinate(index + 1, coord.first().toInt(), coord[1].toInt()) } fun maxXAndMaxY(coords: List<Coordinate>): Pair<Int, Int> { val (_, x) = coords.maxBy { it.x }!! val (_, _, y) = coords.maxBy { it.y }!! return Pair(x, y) } fun mapAreaOfCoords(maxX: Int, maxY: Int, points: List<Coordinate>): List<Coordinate> { return (0..maxX).map { x -> (0..maxY).map { y -> val isPoint = points.firstOption { it.x == x && it.y == y } when (isPoint) { is Some -> isPoint.t.copy( atEdge = Pair(isPoint.t.x, isPoint.t.y).isAtEdge(maxX, maxY), total = Pair(isPoint.t.x, isPoint.t.y).getTotalDistance(points) ) else -> Coordinate( id = -1, x = x, y = y, nearest = nearestCoordOf(x, y, points), atEdge = Pair(x, y).isAtEdge(maxX, maxY), total = Pair(x, y).getTotalDistance(points) ) } } }.flatten() } fun nearestCoordOf(x: Int, y: Int, points: List<Coordinate>): Int { val distance: Map.Entry<Int, List<Pair<Int, Int>>> = points.map { val distance = (it.x - x).absoluteValue + (it.y - y).absoluteValue Pair(it.id, distance) } .groupBy { it.second } .minBy { it.key }!! return if (distance.value.size == 1) distance.value.first().first else -1 } fun Pair<Int, Int>.isAtEdge(maxX: Int, maxY: Int): Boolean { return this.first == 0 || this.first == maxX || this.second == 0 || this.second == maxY } fun maxOfFiniteArea(coords: List<Coordinate>): Int { val finiteAreas: Map<Int, List<Coordinate>> = coords.groupBy { it.nearest }.filterNot { it.value.exists { c -> c.atEdge } } val max = finiteAreas.maxBy { it.value.size }!! return max.value.size } fun Pair<Int, Int>.getTotalDistance(points: List<Coordinate>): Int { return points.fold(0) { acc, coordinate -> acc + ((this.first - coordinate.x).absoluteValue + (this.second - coordinate.y).absoluteValue) } } fun List<Coordinate>.getRegion(maxDistance: Int): List<Coordinate> { return this.filter { it.total < maxDistance } } fun day6Part1(lines: List<String>): Int { val parsedInput = parseInput(lines) val (maxX, maxY) = maxXAndMaxY(parsedInput) val area = mapAreaOfCoords(maxX, maxY, parsedInput) return maxOfFiniteArea(area) } fun day6Part2(lines: List<String>): Int { val parsedInput = parseInput(lines) val (maxX, maxY) = maxXAndMaxY(parsedInput) val area = mapAreaOfCoords(maxX, maxY, parsedInput) return area.getRegion(10000).size }
0
Kotlin
0
0
259cb440369e9e0a5ce8fc522e672753014efdf2
3,437
advent-of-code-2018
MIT License
src/y2022/Day23.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.Cardinal import util.Cardinal.EAST import util.Cardinal.NORTH import util.Cardinal.SOUTH import util.Cardinal.WEST import util.Cardinal.entries import util.Pos import util.minMax import util.neighbors import util.readInput import java.util.Collections object Day23 { private fun parse(input: List<String>): Set<Pos> { return input .mapIndexed { row, s -> s.mapIndexed { col, c -> if (c == '#') row to col else null } }.flatten().filterNotNull() .toSet() } val dirSequence = sequence { val dirs = entries while (true) { yield(dirs.toList()) Collections.rotate(dirs, -1) } } fun Pos.neighborsIn(d: Cardinal): List<Pos> { val ortho = d.of(this) return when (d) { NORTH, SOUTH -> listOf(ortho, EAST.of(ortho), WEST.of(ortho)) WEST, EAST -> listOf(ortho, NORTH.of(ortho), SOUTH.of(ortho)) } } fun part1(input: List<String>): Int { var elfPositions = parse(input) val iter = dirSequence.iterator() repeat(10) { val newPositions = moveElvesOnce(iter, elfPositions) if (newPositions.size != elfPositions.size) error("number of elves changed! ${elfPositions.size} -> ${newPositions.size}") elfPositions = newPositions } val (minP, maxP) = minMax(elfPositions) return (maxP.first - minP.first + 1) * (maxP.second - minP.second + 1) - elfPositions.size } private fun moveElvesOnce( iter: Iterator<List<Cardinal>>, elfPositions: Set<Pos>, ): Set<Pos> { val dirs = iter.next() val (stable, unstable) = elfPositions.partition { it.neighbors().all { n -> n !in elfPositions } } val proposes = unstable.groupBy { p -> dirs.firstOrNull { d -> p.neighborsIn(d).all { it !in elfPositions } }?.of(p) } val blocked = proposes[null] ?: listOf() val (moved, conflict) = proposes.keys.filterNotNull().partition { proposes[it]?.size == 1 } val conflicted = conflict.flatMap { proposes[it] ?: listOf() } return (stable + blocked + moved + conflicted).toSet() } fun part2(input: List<String>): Int { var elfPositions = parse(input) val iter = dirSequence.iterator() var roundNumber = 1 while (true) { val newPositions = moveElvesOnce(iter, elfPositions) if (newPositions == elfPositions) { return roundNumber } else { elfPositions = newPositions roundNumber++ } } } } fun main() { val testInput = """ ....#.. ..###.# #...#.# .#...## #.###.. ##.#.## .#..#.. """.trimIndent().split("\n") println("------Tests------") println(Day23.part1(testInput)) println(Day23.part2(testInput)) println("------Real------") val input = readInput("resources/2022/day23") println(Day23.part1(input)) println(Day23.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
3,195
advent-of-code
Apache License 2.0
src/Day02.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
private enum class Hand(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); val loser get() = when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } val winner get() = when (this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } fun scoreAgainst(other: Hand) = score + when (other) { loser -> Result.WIN this -> Result.TIE else -> Result.LOSS }.score } private enum class Result(val score: Int) { WIN(6), TIE(3), LOSS(0); } fun main() { fun String.toHand() = when (this) { "A", "X" -> Hand.ROCK "B", "Y" -> Hand.PAPER "C", "Z" -> Hand.SCISSORS else -> throw IllegalArgumentException() } fun String.toResult() = when (this) { "X" -> Result.LOSS "Y" -> Result.TIE "Z" -> Result.WIN else -> throw IllegalArgumentException() } fun solve(opponentHand: Hand, desiredResult: Result): Hand = when (desiredResult) { Result.WIN -> opponentHand.winner Result.TIE -> opponentHand Result.LOSS -> opponentHand.loser } fun part1(input: List<String>): Int = input.sumOf { val (other, mine) = it.split(' ') mine.toHand().scoreAgainst(other.toHand()) } fun part2(input: List<String>): Int = input.sumOf { val (left, right) = it.split(' ') val opponentHand = left.toHand() val desiredResult = right.toResult() solve(opponentHand, desiredResult).scoreAgainst(opponentHand) } // 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
0
afbcec6a05b8df34ebd8543ac04394baa10216f0
1,880
advent-of-code-22
Apache License 2.0
src/Day11.kt
bigtlb
573,081,626
false
{"Kotlin": 38940}
class Monkey( val items: ArrayDeque<Long>, val monkeyOperation: (new: Long) -> Long, val modVal:Long, val trueMonkey:Int, val falseMonkey:Int, val worryLevel: Long = 3 ) { var counter = 0L fun throwThings(monkeys: List<Monkey>) { val mod = monkeys.map{it.modVal}.reduce(Long::times) while (items.isNotEmpty()) { val item = items.removeFirst() counter++ val newItemVal = Math.floorDiv(monkeyOperation(item), worryLevel) % mod monkeys[if(newItemVal.rem(modVal) == 0L) trueMonkey else falseMonkey].items.add(newItemVal) } } companion object { fun load(lines: List<String>, worry:Boolean): Monkey { val items: ArrayDeque<Long> = ArrayDeque() var op: ((new: Long) -> Long)? = null var modVal = 0L var trueMonkey = 0 var falseMonkey = 0 lines.mapIndexed { idx, line -> when { line.contains("items:") -> items.addAll( line.takeLastWhile { it != ':' }.split(',').map { it.trim().toLong() }) line.contains("Operation:") -> { val terms = line.takeLastWhile { it != ':' }.split(' ') op = fun(old: Long): Long { val secondVal = terms.last().toLongOrNull() ?: old return when (terms[4]) { "+" -> old + secondVal "*" -> old * secondVal else -> old } } } line.contains("Test:") -> { modVal = line.takeLastWhile { it != ' ' }.toLong() trueMonkey = lines[idx + 1].takeLastWhile { it != ' ' }.toInt() falseMonkey = lines[idx + 2].takeLastWhile { it != ' ' }.toInt() } else -> Unit } } return Monkey(items, op!!, modVal, trueMonkey, falseMonkey, if (worry) 3L else 1L) } } } fun main() { fun List<Monkey>.throwThings() { forEach { monkey -> monkey.throwThings(this) } } val monkeyRegex = """Monkey \d+:$""".toRegex() fun loadMonkeys(input: List<String>, worry:Boolean=true): List<Monkey> = (input.mapIndexed { idx, line -> if (monkeyRegex.matches(line)) idx else -1 }.filter { it != -1 } + listOf(-1)) .windowed(2) { (startIdx, nextIdx) -> Monkey.load(input.subList(startIdx, if (nextIdx == -1) input.size else nextIdx), worry) } fun part1(input: List<String>): Long { val monkeys = loadMonkeys(input) repeat(20) { _ -> monkeys.throwThings() } return monkeys.sortedByDescending { it -> it.counter }.take(2).let { (one, two) -> one.counter * two.counter } } fun part2(input: List<String>): Long { val monkeys = loadMonkeys(input, false) repeat(10000) { _ -> monkeys.throwThings() } return monkeys.sortedByDescending { it -> it.counter }.take(2).let { (one, two) -> one.counter * two.counter } } // 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
d8f76d3c75a30ae00c563c997ed2fb54827ea94a
3,540
aoc-2022-demo
Apache License 2.0
src/day24/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day24 import Coord import closeNeighbours import day06.main import readInput import java.util.* import kotlin.math.abs fun main() { data class Step(val coord: Coord, val time: Int) { fun distanceTo(point: Pair<Int, Int>) = abs(point.first - coord.first) + abs(point.second - coord.second) fun estimate(point: Pair<Int, Int>) = time + distanceTo(point) } data class Maze(val map: List<Pair<Coord, Char>>) { val walls = map.filter { it.second == '#' }.map { it.first }.toSet() val maxX = walls.maxOf { it.first } val maxY = walls.maxOf { it.second } val start = Coord(first = 0, second = -1) val end = Coord(first = maxX - 1, second = maxY) val horizontalBlizzards = (0 until maxX).associateWith { time -> (0..maxY).flatMap { row -> map.filter { it.second == '>' || it.second == '<' }.groupBy { it.first.second } .mapValues { (_, blizzards) -> blizzards.map { (c, direction) -> if (direction == '>') { c.copy(first = (c.first + time) % maxX) } else { c.copy(first = ((c.first - time) % maxX + maxX) % maxX) } } }[row].orEmpty() }.toSet() } val verticalBlizzards = (0 until maxY).associateWith { time -> (0 until maxX).flatMap { map.filter { it.second == '^' || it.second == 'v' }.groupBy { it.first.first } .mapValues { (_, blizzards) -> blizzards.map { (c, direction) -> if (direction == 'v') { c.copy(second = (c.second + time) % maxY) } else { c.copy(second = ((c.second - time) % maxY + maxY) % maxY) } } }[it].orEmpty() }.toSet() } fun isValid(nextStep: Step) = nextStep.coord !in walls && nextStep.coord !in horizontalBlizzards[nextStep.time % maxX]!! && nextStep.coord !in verticalBlizzards[nextStep.time % maxY]!! && nextStep.coord.first in 0 until maxX && nextStep.coord.second in 0 until maxY fun distance(from: Coord = start, destination: Coord = end, time: Int = 0): Int { val queue = PriorityQueue<Step>(compareBy { it.distanceTo(destination) }) queue.add(Step(from, time)) var minTime = Int.MAX_VALUE val seen = mutableSetOf<Step>() while (queue.isNotEmpty()) { val step = queue.remove()!! if (step in seen || step.time > minTime || step.estimate(destination) >= minTime) continue seen.add(step) if (step.coord == destination) { minTime = minOf(minTime, step.time) } else { queue.addAll((step.coord.closeNeighbours + step.coord).map { Step(it, step.time + 1) }.filter { it.coord == destination || it.coord == from || (it !in seen && this.isValid(it)) }) } } return minTime } } fun parse(input: List<String>) = Maze(input.flatMapIndexed { y, s -> s.mapIndexedNotNull { x, c -> (Coord(x - 1, y - 1) to c).takeIf { it.second != '.' } } }) fun part1(input: Maze) = input.distance() fun part2(input: Maze) = with(input) { distance( from = input.start, destination = input.end, time = distance( from = input.end, destination = input.start, time = distance( from = input.start, destination = input.end ) ) ) } val input = parse(readInput(::main.javaClass.packageName)) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
4,210
AOC2022
Apache License 2.0
src/Day08.kt
psy667
571,468,780
false
{"Kotlin": 23245}
fun main() { val id = "08" fun parse(input: List<String>): List<List<Int>> { return input.map { it.split("").drop(1).dropLast(1).map(String::toInt) } } fun part1(input: List<String>): Int { val treesMatrix = parse(input) val size = treesMatrix.size val visibilityMatrix = List(size) { MutableList(size) { 0 } } listOf( 0 until size, size.dec() downTo 0 ).forEach { val range = it for (y in range) { var maxInRow = -1 for (x in range) { if (treesMatrix[y][x] > maxInRow) { visibilityMatrix[y][x] = 1 maxInRow = treesMatrix[y][x] } } } } listOf( 0 until size, size.dec() downTo 0 ).forEach { val range = it for (x in range) { var maxInRow = -1 for (y in range) { if (treesMatrix[y][x] > maxInRow) { visibilityMatrix[y][x] = 1 maxInRow = treesMatrix[y][x] } } } } return visibilityMatrix.sumOf { it.sum() } } fun part2(input: List<String>): Int { val treesMatrix = parse(input) val size = treesMatrix.size var maxValue = 0 for (y in 1 until size-1) { for (x in 1 until size-1) { var totalRes = 1 listOf( listOf(1, 0), listOf(-1, 0), listOf(0, 1), listOf(0, -1) ).forEach { var res = 0 val (mY, mX) = it var (nY, nX) = listOf(y + mY, x + mX) while (nY < size && nX < size && nY >= 0 && nX >= 0) { res++ if (treesMatrix[nY][nX] >= treesMatrix[y][x]) { break } nY += mY nX += mX } totalRes *= res } maxValue = maxOf(maxValue, totalRes) } } return maxValue } val testInput = readInput("Day${id}_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day${id}") println("==== DAY $id ====") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
73a795ed5e25bf99593c577cb77f3fcc31883d71
2,665
advent-of-code-2022
Apache License 2.0
src/day05/solution.kt
bohdandan
729,357,703
false
{"Kotlin": 80367}
package day05 import println import readInput fun main() { class MappingLine(val destinationRangeStart: Long, val sourceRangeStart: Long, val rangeLength: Long) { fun isApplicable(input: Long): Boolean { return sourceRangeStart <= input && sourceRangeStart + rangeLength > input } fun map(input: Long): Long { var position = input - sourceRangeStart return destinationRangeStart + position } } class Mapping(var name: String, var level: Int, var mappingLines: List<MappingLine>) { fun map(input: Long): Long { var mappingLine = mappingLines.find { it.isApplicable(input)} if (mappingLine == null) { return input } else { return mappingLine.map(input) } } } class Almanac { var seeds: List<Long> = emptyList() var mappings: List<Mapping> = emptyList() var seedRanges: Boolean = false constructor(input: List<String>, seedRangesInput: Boolean = false) { seedRanges = seedRangesInput var beginningOfBlock = true var level = 0 for ((index, row) in input.withIndex()) { if (index == 0) { val numbers = "\\d+".toRegex().findAll(row) .map { it.value.toLong() } .toList() seeds = numbers continue } if (row.isEmpty()) { beginningOfBlock = true continue } if (beginningOfBlock) { beginningOfBlock = false mappings += Mapping(row, level++, emptyList()) continue } else { val numbers = row.split(" ") mappings.last().mappingLines += MappingLine(numbers[0].toLong(), numbers[1].toLong(), numbers[2].toLong()) } } } fun mapThrough(seed: Long): Long { var nextLevelValue = seed; mappings.forEach{ nextLevelValue = it.map(nextLevelValue) } return nextLevelValue; } fun lowestNumber(): Long { if (seedRanges) { var min = Long.MAX_VALUE for (i in seeds.indices step 2) { "Interval $i".println() (seeds[i]..<seeds[i] + seeds[i + 1]).forEach { val mapped = mapThrough(it) if (mapped < min) { min = mapped } } } return min; } else { return seeds.map { mapThrough(it) }.min(); } } } val testAlmanac = Almanac(readInput("day05/test1")) check(testAlmanac.lowestNumber() == 35L) val almanac = Almanac(readInput("day05/input")) almanac.lowestNumber().println() val testAlmanac2 = Almanac(readInput("day05/test1"), true) check(testAlmanac2.lowestNumber() == 46L) val almanac2 = Almanac(readInput("day05/input"), true) almanac2.lowestNumber().println() }
0
Kotlin
0
0
92735c19035b87af79aba57ce5fae5d96dde3788
3,315
advent-of-code-2023
Apache License 2.0
src/year_2023/day_02/Day02.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2023.day_02 import readInput data class Game( val round: Int, var isPossible: Boolean, var power: Int = 0 ) data class GameCube( val name: String, val maxCount: Int, var minPossible: Int = 0 ) { fun reset() { minPossible = 0 } } object Day02 { /** * */ fun solutionOne(text: List<String>): Int { var total = 0 text.forEach { line -> val halves = line.split(":") val pulls = halves[1].replace(";", ",").split(", ") val possible = pulls.none { pull -> val split = pull.trim().split(" ") val count = split[0].toInt() when (split[1]) { "red" -> count > 12 "green" -> count > 13 "blue" -> count > 14 else -> true } } val game = Game( round = halves[0].split(" ")[1].toInt(), isPossible = possible ) if (possible) { total += game.round } } return total } /** * */ fun solutionTwo(text: List<String>): Int { val cubes = listOf( GameCube("red", 0), GameCube("green", 0), GameCube("blue", 0), ) var total = 0 text.forEach { line -> cubes.forEach { it.reset() } val halves = line.split(":") val pulls = halves[1].replace(";", ",").split(", ") pulls.forEach { pull -> val split = pull.trim().split(" ") val count = split[0].toInt() val color = split[1] val cube = cubes.first { it.name == color } if (cube.minPossible < count) { cube.minPossible = count } } var gamePower = 1 cubes.forEach { cube -> gamePower *= cube.minPossible } total += gamePower } return total } } fun main() { val text = readInput("year_2023/day_02/Day02.txt") val solutionOne = Day02.solutionOne(text) println("Solution 1: $solutionOne") val solutionTwo = Day02.solutionTwo(text) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
2,103
advent_of_code
Apache License 2.0
src/y2023/Day08.kt
a3nv
574,208,224
false
{"Kotlin": 34115, "Java": 1914}
package y2023 import utils.readInput fun main() { fun Pair<String, String>.pickDirection(dir: Char): String { return if ('L' == dir) this.first else this.second } fun part1(input: List<String>): Int { val pattern = input.first() val ruleSeq = generateSequence(0) { (it + 1) % pattern.length }.map { pattern[it] } val map = input.drop(2).filter { it.isNotBlank() } .associate { val key = it.substringBefore(" =") val (left, right) = it.substringAfter("= (").substringBefore(")").split(", ") key to Pair(left, right) } return ruleSeq.runningFold("AAA") { node, rule -> map[node]!!.pickDirection(rule) }.takeWhile { it != "ZZZ" }.count() } fun gcd(a: Long, b: Long): Long { if (b == 0L) return a return gcd(b, a % b) } fun part2(input: List<String>): Int { val pattern = input.first() val ruleSeq = generateSequence(0) { (it + 1) % pattern.length }.map { pattern[it] } val map = input.drop(2).filter { it.isNotBlank() } .associate { val key = it.substringBefore(" =") val (left, right) = it.substringAfter("= (").substringBefore(")").split(", ") key to Pair(left, right) } val startingNodes = map.filter { it.key.endsWith("A") }.keys.toSet() val map1 = startingNodes.map { startingNode -> ruleSeq.runningFold(startingNode) { currentNode, rule -> println("$startingNode -> $rule") map[currentNode]!!.pickDirection(rule) }.takeWhile { !it.endsWith("Z") }.count() } // this is the most important part val reduce = map1.map { it.toLong() }.reduce { a, b -> println("$a (a) * $b (b) / ${gcd(a,b)} (gcd)") a * b / gcd(a, b) } println(reduce) return 0 } // test if implementation meets criteria from the description, like: var testInput = readInput("y2023", "Day08_test_part1") // println(part1(testInput)) // check(part1(testInput) == 6440L) println(part2(testInput)) // check(part2(testInput) == 251927063) val input = readInput("y2023", "Day08") println(part1(input)) // check(part1(input) == 251927063L) println(part2(input)) // check(part2(input) == 255632664) }
0
Kotlin
0
0
ab2206ab5030ace967e08c7051becb4ae44aea39
2,426
advent-of-code-kotlin
Apache License 2.0
src/Day04.kt
virtualprodigy
572,945,370
false
{"Kotlin": 8043}
fun main() { data class Range(val start: Int, val end: Int) fun part1(input: List<String>): Int { var total = 0 for(pair in input){ val ranges = pair.split(",").map { str -> val split = str.split("-") Range(split[0].toInt(),split[1].toInt()) } val range1 = ranges[0] val range2 = ranges[1] if( (range1.start >= range2.start && range1.end <= range2.end) || (range2.start >= range1.start && range2.end <= range1.end)){ total += 1 } } return total } fun part2(input: List<String>): Int { var total = 0 for(pair in input){ val ranges = pair.split(",").map { str -> val split = str.split("-") Range(split[0].toInt(),split[1].toInt()) } val range1 = ranges[0] val range2 = ranges[1] if( ( (range1.start >= range2.start && range1.start <= range2.end) || (range1.end >= range2.start && range1.end <= range2.end) ) || ( (range2.start >= range1.start && range2.start <= range1.end) || (range2.end >= range1.start && range2.end <= range1.end) ) ){ total += 1 } } // println("total is $total") return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
025f3ae611f71a00e9134f0e2ba4b602432eea93
1,700
advent-code-code-kotlin-jetbrains-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1489/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1489 /** * LeetCode page: [1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree](https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/); */ class Solution { /* Complexity: * Time O(E^2 * Log n) and Space O(E) where E is the size of edges; */ fun findCriticalAndPseudoCriticalEdges(n: Int, edges: Array<IntArray>): List<List<Int>> { val sortedEdges = sortedEdges(edges) // Sorted by monotonically increasing weight val mstWeight = checkNotNull(mstWeight(n, sortedEdges)) val criticalEdges = criticalEdges(n, sortedEdges, mstWeight) val pseudoCriticalEdges = pseudoCriticalEdges(n, sortedEdges, criticalEdges, mstWeight) return listOf(criticalEdges.map { it.index }, pseudoCriticalEdges.map { it.index }) } private data class Edge(val u: Int, val v: Int, val weight: Int, val index: Int) private fun sortedEdges(edges: Array<IntArray>): List<Edge> { val result = edges.mapIndexedTo(mutableListOf()) { index, array -> Edge(array[0], array[1], array[2], index) } result.sortBy { edge -> edge.weight } return result } /** * Return the MST weight, or null if the graph is not connected. * * If [mandatedExclusion] and [mandatedInclusion] are not disjoint, the result * is unexpected. */ private fun mstWeight( n: Int, sortedEdges: List<Edge>, mandatedInclusion: Set<Edge> = emptySet(), mandatedExclusion: Set<Edge> = emptySet() ): Int? { var result = 0 val unionFind = UnionFind(n) for (edge in mandatedInclusion) { unionFind.union(edge.u, edge.v) result+= edge.weight } for (edge in sortedEdges) { if (edge in mandatedExclusion) { continue } if (unionFind.union(edge.u, edge.v)) { result += edge.weight } } val isConnected = unionFind.numComponents == 1 return if (isConnected) result else null } private class UnionFind(size: Int) { private val parents = IntArray(size) { it } private val ranks = IntArray(size) var numComponents = size private set fun union(x: Int, y: Int): Boolean { val xRoot = find(x) val yRoot = find(y) if (xRoot == yRoot) { return false } when { ranks[xRoot] < ranks[yRoot] -> parents[xRoot] = yRoot ranks[yRoot] < ranks[xRoot] -> parents[yRoot] = xRoot else -> { parents[yRoot] = xRoot ranks[xRoot]++ } } numComponents-- return true } private fun find(x: Int): Int { if (parents[x] != x) { parents[x] = find(parents[x]) } return parents[x] } } private fun criticalEdges(n: Int, sortedEdges: List<Edge>, mstWeight: Int): Set<Edge> { val result = hashSetOf<Edge>() /* Find all critical edges: * If excluding an edge results in an increase in the MST weight or makes the graph * no longer connected, then it is a critical edge; */ for (excludedEdge in sortedEdges) { val newMstWeight = mstWeight( n = n, sortedEdges = sortedEdges, mandatedExclusion = hashSetOf(excludedEdge) ) if (newMstWeight == null || newMstWeight > mstWeight) { result.add(excludedEdge) } } return result } private fun pseudoCriticalEdges( n: Int, sortedEdges: List<Edge>, criticalEdges: Set<Edge>, mstWeight: Int ): Set<Edge> { val result = hashSetOf<Edge>() /* Find all pseudo-critical edges: * If an edge is not critical, but including it does not increase the MST weight, * then it is a pseudo-critical edge; */ for (includedEdge in sortedEdges) { if (includedEdge in criticalEdges) { continue } val newMstWeight = mstWeight( n = n, sortedEdges = sortedEdges, mandatedInclusion = hashSetOf(includedEdge) ) if (newMstWeight == mstWeight) { result.add(includedEdge) } } return result } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
4,652
hj-leetcode-kotlin
Apache License 2.0
src/day14/Day14.kt
xxfast
572,724,963
false
{"Kotlin": 32696}
package day14 import geometry.* import readLines val SOURCE: Point = 500L to 0L val FALL_ORDER: List<Vector> = listOf(0L to +1L, -1L to +1L, +1L to +1L) data class Simulation(val source: Point = SOURCE, val sand: MutableSet<Point> = mutableSetOf(), val rock: Set<Point>) val Simulation.points get() = sand + rock fun Simulation(paths: List<Path>): Simulation = Simulation( rock = paths .map { path: Path -> path.windowed(2).map { (start, end) -> start..end }.flatten().distinct() } .flatten() .toSet() ) fun Simulation.flow(from: Point) = from .let { (x, y) -> FALL_ORDER.asSequence().map { vector -> from + vector } } .filterNot { point -> point in this.rock || point.second >= rock.maxY + 2 } fun format(input: List<String>): List<Path> = input .map { line -> line.split("->").map { point -> point.trim().split(",").let { (x, y) -> x.toLong() to y.toLong() } } } operator fun Simulation.contains(point: Point): Boolean = point.y < rock.maxY fun main() { fun simulate(path: List<Path>, void: Boolean): Int { val simulation = Simulation(path) var current: Point = simulation.source while (simulation.source !in simulation.sand) { val next = simulation.flow(current).firstOrNull { it !in simulation.sand } if (next == null) simulation.sand += current current = next ?: simulation.source if (void && current !in simulation) break } return simulation.sand.size } fun part1(input: List<String>): Int = simulate(format(input), void = true) fun part2(input: List<String>): Int = simulate(format(input), void = false) val testInput = readLines("day14/test.txt") val input = readLines("day14/input.txt") check(part1(testInput) == 24) println(part1(input)) check(part2(testInput) == 93) println(part2(input)) } // For debug fun println(simulation: Simulation) { for (y in simulation.points.minY..simulation.points.maxY) { for (x in simulation.points.minX..simulation.points.maxX) { val symbol = when (x to y) { simulation.source -> '+' in simulation.rock -> '█' in simulation.sand -> 'o' else -> ' ' } print(symbol) } println() } }
0
Kotlin
0
1
a8c40224ec25b7f3739da144cbbb25c505eab2e4
2,191
advent-of-code-22
Apache License 2.0
src/Day16.kt
MickyOR
578,726,798
false
{"Kotlin": 98785}
import kotlin.math.* fun main() { var nodes: Int = 16 var dp = Array(1 shl nodes) { Array(nodes) { IntArray(31) { -1 } } } var dist = Array(60) { IntArray(60) { 10000000 } } var flow = IntArray(60) { 0 } var g = Array(60) { mutableListOf<Int>() } var id = mutableMapOf<String, Int>() fun f(mask: Int, v: Int, t: Int) : Int { if (t < 0) return -10000000 if (mask == 0) return 0 if (dp[mask][v][t] != -1) return dp[mask][v][t] var res = 0 for (i in 0 until nodes) { if (mask and (1 shl i) != 0) { res = max(res, f(mask xor (1 shl i), i, t-1-dist[v][i]) + (t-1-dist[v][i])*flow[i]) } } dp[mask][v][t] = res return res } fun part1(input: List<String>): Int { id["AA"] = 15 for (line in input) { if (line.isEmpty()) continue var vs = line.split(" ").map { if (it.last() == ';' || it.last() == ',') it.dropLast(1) else it } vs = vs.map { if (it.length >= 5 && it.substring(0, 5) == "rate=") it.drop(5) else it } if (vs[4].toInt() == 0) continue if (!id.containsKey(vs[1])) id[vs[1]] = id.size-1 } for (line in input) { if (line.isEmpty()) continue var vs = line.split(" ").map { if (it.last() == ';' || it.last() == ',') it.dropLast(1) else it } vs = vs.map { if (it.length >= 5 && it.substring(0, 5) == "rate=") it.drop(5) else it } if (!id.containsKey(vs[1])) id[vs[1]] = id.size var v = id[vs[1]]!! dist[v][v] = 0 g[v].add(v) flow[v] = vs[4].toInt() for (i in 9 until vs.size) { if (!id.containsKey(vs[i])) id[vs[i]] = id.size var u = id[vs[i]]!! dist[v][u] = 1 g[v].add(u) } } for (k in 0 until 60) { for (i in 0 until 60) { for (j in 0 until 60) { dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) } } } return f((1 shl nodes)-1, 15, 30) } fun part2(input: List<String>): Int { // flow and dist are already calculated var ans = 0 for (mask in 0 until (1 shl (nodes-1))) { var mask1 = mask or (1 shl 15) var mask2 = ((1 shl (nodes))-1) xor mask ans = max(ans, f(mask1, 15, 26) + f(mask2, 15, 26)) } return ans } val input = readInput("Day16") part1(input).println() part2(input).println() }
0
Kotlin
0
0
c24e763a1adaf0a35ed2fad8ccc4c315259827f0
2,734
advent-of-code-2022-kotlin
Apache License 2.0
codeforces/round616/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round616 fun solve(k: Int, toSwitch: List<Int>, where: List<List<Int>>): List<Int> { val p = MutableList(k) { it } val odd = MutableList(k) { 0 } val d = List(k) { mutableListOf(0, 1) } fun get(x: Int): Int { if (p[x] == x) return x val par = p[x] p[x] = get(par) odd[x] = odd[x] xor odd[par] return p[x] } fun spend(x: Int): Int { if (where[x].isEmpty()) return 0 if (where[x].size == 1) { val (a) = where[x] val aa = get(a) val old = d[aa].minOrNull()!! d[aa][odd[a] xor toSwitch[x] xor 1] = k + 1 return d[aa].minOrNull()!! - old } val (a, b) = where[x].let { if ((x + it.hashCode()) % 2 == 0) it else it.reversed() } val (aa, bb) = get(a) to get(b) if (aa == bb) return 0 p[aa] = bb odd[aa] = odd[a] xor odd[b] xor toSwitch[x] val old = d[aa].minOrNull()!! + d[bb].minOrNull()!! for (i in 0..1) { d[bb][i] = minOf(d[bb][i] + d[aa][i xor odd[aa]], k + 1) } return d[bb].minOrNull()!! - old } var ans = 0 return toSwitch.indices.map { ans += spend(it); ans } } fun main() { val (_, k) = readInts() val toSwitch = readLn().map { '1' - it } val where = List(toSwitch.size) { mutableListOf<Int>() } repeat(k) { i -> readLn() readInts().forEach { where[it - 1].add(i) } } println(solve(k, toSwitch, where).joinToString("\n")) } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,461
competitions
The Unlicense
src/day05/Day05.kt
spyroid
433,555,350
false
null
package day05 import readInput import java.awt.Point import kotlin.math.sign fun main() { fun move(p1: Point, p2: Point): Sequence<Point> = sequence { val dx = (p2.x - p1.x).sign val dy = (p2.y - p1.y).sign var x = p1.x var y = p1.y while (x != p2.x + dx || y != p2.y + dy) { yield(Point(x, y)) x += dx y += dy } } fun overlaps(seq: Sequence<Pair<Point, Point>>): Int { val map = mutableMapOf<Point, Int>() return seq.forEach { move(it.first, it.second).forEach { point -> map.merge(point, 1) { a, b -> a + b } } }.let { map.values.count { it >= 2 } } } fun part1(seq: Sequence<Pair<Point, Point>>) = overlaps(seq.filter { it.first.x == it.second.x || it.first.y == it.second.y }) fun part2(seq: Sequence<Pair<Point, Point>>) = overlaps(seq) val testSeq = readInput("day05/test").asSequence().map { toPairPoints(it) } val inputSeq = readInput("day05/input").asSequence().map { toPairPoints(it) } val res1 = part1(testSeq) check(res1 == 5) { "Expected 5 but got $res1" } println("Part1: ${part1(inputSeq)}") val res2 = part2(testSeq) check(res2 == 12) { "Expected 12 but got $res2" } println("Part2: ${part2(inputSeq)}") } val regex = "(\\d+),(\\d+) -> (\\d+),(\\d+)".toRegex() fun toPairPoints(line: String): Pair<Point, Point> { return regex.find(line)!!.groupValues.drop(1).map { it.toInt() } .let { Pair(Point(it[0], it[1]), Point(it[2], it[3])) } }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
1,553
Advent-of-Code-2021
Apache License 2.0
src/Day02.kt
fasfsfgs
573,562,215
false
{"Kotlin": 52546}
import java.lang.IllegalArgumentException enum class Shape(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3), } fun getOpponentsShape(strShape: String): Shape { return when (strShape) { "A" -> Shape.ROCK "B" -> Shape.PAPER "C" -> Shape.SCISSORS else -> throw IllegalArgumentException() } } fun getMyShape(strShape: String): Shape { return when (strShape) { "X" -> Shape.ROCK "Y" -> Shape.PAPER "Z" -> Shape.SCISSORS else -> throw IllegalArgumentException() } } class Play(private val opponentsShape: Shape, val myShape: Shape) { fun getResult(): Int { return when { opponentsShape == myShape -> 3 myShape == Shape.ROCK && opponentsShape == Shape.SCISSORS -> 6 myShape == Shape.SCISSORS && opponentsShape == Shape.PAPER -> 6 myShape == Shape.PAPER && opponentsShape == Shape.ROCK -> 6 else -> 0 } } } fun getMyShape(opponentsShape: Shape, strOutcome: String): Shape { val outcome = when (strOutcome) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> throw IllegalArgumentException() } return Shape.values() .find { Play(opponentsShape, it).getResult() == outcome } ?: throw Exception() } fun main() { fun part1(input: List<String>): Int { return input .map { val (strOpponent, strMe) = it.split(" ") Play(getOpponentsShape(strOpponent), getMyShape(strMe)) } .sumOf { it.getResult() + it.myShape.points } } fun part2(input: List<String>): Int { return input .map { val (strOpponent, strOutcome) = it.split(" ") val opponentsShape = getOpponentsShape(strOpponent) val myShape = getMyShape(opponentsShape, strOutcome) Play(getOpponentsShape(strOpponent), myShape) } .sumOf { it.getResult() + it.myShape.points } } // 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
0
17cfd7ff4c1c48295021213e5a53cf09607b7144
2,311
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2016/Day24.kt
tginsberg
74,924,040
false
null
/* * Copyright (c) 2016 by <NAME> */ package com.ginsberg.advent2016 import com.ginsberg.advent2016.utils.asDigit import java.util.ArrayDeque /** * Advent of Code - Day 24: December 24, 2016 * * From http://adventofcode.com/2016/day/24 * */ class Day24(val input: List<String>) { val board: List<List<Spot>> = parseInput() val numberedSpots: Map<Int, Spot> = findNumberedSpots(board) val distances: Map<Pair<Int, Int>, Int> = mapAllDistances(numberedSpots) private fun mapAllDistances(numberedSpots: Map<Int, Spot>): Map<Pair<Int, Int>, Int> { val oneWay = numberedSpots.flatMap { l -> numberedSpots.filter { l.key < it.key }.map { r -> Pair(l.key, r.key) to search(l.value, r.value) } }.toMap() return oneWay.plus(oneWay.map { Pair(it.key.second, it.key.first) to it.value }) } fun solvePart1(): Int = findMinPath(numberedSpots.keys) fun solvePart2(): Int = findMinPath(numberedSpots.keys, true) fun search(from: Spot, to: Spot): Int { val visited = mutableMapOf(from to 0) val queue = ArrayDeque<Spot>().apply { add(from) } while (queue.isNotEmpty()) { val current = queue.poll() val dist = visited[current]!! if (current == to) { return dist } val neighbors = listOf( board[current.x][current.y - 1], board[current.x][current.y + 1], board[current.x - 1][current.y], board[current.x + 1][current.y]) .filter { it.isValid() && !it.isWall() } .filterNot { it in visited } visited.putAll(neighbors.map { it to dist + 1 }) queue.addAll(neighbors) } return 0 } private fun parseInput(): List<List<Spot>> = (0..input.size - 1).map { x -> (0..input[x].length - 1).map { y -> Spot(x, y, input[x][y]) } } private fun findNumberedSpots(board: List<List<Spot>>): Map<Int, Spot> = board.flatMap { it.filter { it.getGoalNumber() != null } }.associateBy { it.getGoalNumber()!! } private fun findMinPath(all: Set<Int>, loopBack: Boolean = false): Int { fun inner(unvisited: Set<Int>, at: Int = 0, acc: Int = 0): Int = if (unvisited.isEmpty()) acc + (if (loopBack) distances[Pair(at, 0)]!! else 0) else all.filter { it in unvisited }.map { it -> inner(unvisited.minus(it), it, acc + distances[Pair(at, it)]!!) }.min()!! return inner(all.minus(0), 0, 0) } data class Spot(val x: Int, val y: Int, val contains: Char) { fun isValid(): Boolean = x >= 0 && y >= 0 fun isWall(): Boolean = contains == '#' fun getGoalNumber(): Int? = try { contains.asDigit() } catch(e: Exception) { null } } }
0
Kotlin
0
3
a486b60e1c0f76242b95dd37b51dfa1d50e6b321
2,917
advent-2016-kotlin
MIT License
src/main/kotlin/g1801_1900/s1878_get_biggest_three_rhombus_sums_in_a_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1878_get_biggest_three_rhombus_sums_in_a_grid // #Medium #Array #Math #Sorting #Matrix #Heap_Priority_Queue #Prefix_Sum // #2023_06_22_Time_326_ms_(100.00%)_Space_43.8_MB_(100.00%) import java.util.PriorityQueue class Solution { fun getBiggestThree(grid: Array<IntArray>): IntArray { val capicity = 3 val minHeap = PriorityQueue<Int>() val m = grid.size val n = grid[0].size val preSum = Array(m) { Array(n) { IntArray(2) } } val maxLen = Math.min(m, n) / 2 for (r in 0 until m) { for (c in 0 until n) { addToMinHeap(minHeap, grid[r][c], capicity) preSum[r][c][0] += if (valid(m, n, r - 1, c - 1)) grid[r][c] + preSum[r - 1][c - 1][0] else grid[r][c] preSum[r][c][1] += if (valid(m, n, r - 1, c + 1)) grid[r][c] + preSum[r - 1][c + 1][1] else grid[r][c] } } for (r in 0 until m) { for (c in 0 until n) { for (l in 1..maxLen) { if (!valid(m, n, r - l, c - l) || !valid(m, n, r - l, c + l) || !valid(m, n, r - 2 * l, c) ) { break } var rhombus = preSum[r][c][0] - preSum[r - l][c - l][0] rhombus += preSum[r][c][1] - preSum[r - l][c + l][1] rhombus += preSum[r - l][c - l][1] - preSum[r - 2 * l][c][1] rhombus += preSum[r - l][c + l][0] - preSum[r - 2 * l][c][0] rhombus += -grid[r][c] + grid[r - 2 * l][c] addToMinHeap(minHeap, rhombus, capicity) } } } val size = minHeap.size val res = IntArray(size) for (i in size - 1 downTo 0) { res[i] = minHeap.poll() } return res } private fun addToMinHeap(minHeap: PriorityQueue<Int>, num: Int, capicity: Int) { if (minHeap.isEmpty() || minHeap.size < capicity && !minHeap.contains(num)) { minHeap.offer(num) } else { if (num > minHeap.peek() && !minHeap.contains(num)) { minHeap.poll() minHeap.offer(num) } } } private fun valid(m: Int, n: Int, r: Int, c: Int): Boolean { return 0 <= r && r < m && 0 <= c && c < n } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,420
LeetCode-in-Kotlin
MIT License
2023/src/main/kotlin/Day23.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
object Day23 { fun part1(input: String): Int { val maze = parse(input) val start = Pos(maze.first().indexOf('.'), 0) val end = Pos(maze.last().indexOf('.'), maze.size - 1) val queue = java.util.ArrayDeque<Hike>() queue.add(Hike(start.move(Direction.SOUTH), setOf(start))) var longest = 0 while (queue.isNotEmpty()) { val (curr, visited) = queue.poll() if (curr == end) { longest = maxOf(longest, visited.size) continue } val newVisited = visited + curr queue.addAll( Direction.entries .map { it to curr.move(it) } .filter { (direction, newPos) -> val c = maze[newPos.y][newPos.x] return@filter newPos !in visited && c != '#' && ( c == '.' || (c == '>' && direction == Direction.EAST) || (c == 'v' && direction == Direction.SOUTH) || (c == '<' && direction == Direction.WEST) || (c == '^' && direction == Direction.NORTH) ) } .map { (_, newPos) -> Hike(newPos, newVisited) } ) } return longest } fun part2(input: String): Int { val maze = parse(input) val graph = convertMazeToGraph(maze) return longestHike(graph) } private fun longestHike(graph: Graph): Int { val (edges, start, end) = graph val queue = java.util.ArrayDeque<Hike>() queue.add(Hike(start, setOf(start), 0)) var longest = 0 while (queue.isNotEmpty()) { val path = queue.poll() if (path.curr == end) { longest = maxOf(longest, path.distance) continue } // Heuristic that makes it possible to finish this within our lifetime and heap space if (!canGetToEnd(graph, path)) { continue } val nextNodes = edges[path.curr]!!.filter { it.key !in path.visited } queue.addAll( nextNodes.map { Hike(it.key, path.visited + it.key, path.distance + it.value) } ) } return longest } private fun canGetToEnd(graph: Graph, path: Hike): Boolean { val visited = HashSet<Pos>(path.visited - path.curr) val queue = java.util.ArrayDeque<Pos>() queue.add(path.curr) while (queue.isNotEmpty()) { val curr = queue.poll() if (curr in visited) { continue } else if (curr == graph.end) { return true } visited.add(curr) queue.addAll(graph.edges[curr]!!.keys) } return false } private fun convertMazeToGraph(maze: List<String>): Graph { // So we don't have to worry about bounds checks val walledMaze = listOf("#".repeat(maze[0].length)) + maze + listOf("#".repeat(maze[0].length)) val start = Pos(maze.first().indexOf('.'), 1) val end = Pos(maze.last().indexOf('.'), maze.size) val nodes = mutableSetOf<Pos>() val edges = mutableMapOf<Pos, MutableMap<Pos, Int>>() fun addEdge(finder: Edge) { nodes.addAll(setOf(finder.start, finder.curr)) edges.getOrPut(finder.start) { mutableMapOf() }[finder.curr] = finder.distance edges.getOrPut(finder.curr) { mutableMapOf() }[finder.start] = finder.distance } val visited = mutableSetOf<Pos>() val queue = java.util.ArrayDeque<Edge>() queue.add(Edge(start, start, 0)) while (queue.isNotEmpty()) { val finder = queue.poll() val (_, curr, distance) = finder if (curr in visited) { if (curr in nodes) { // Don't restart a search from this node, but record edges addEdge(finder) } continue } visited.add(curr) val next = Direction.entries .map { curr.move(it) } .filter { newPos -> newPos !in visited && walledMaze[newPos.y][newPos.x] != '#' } if (next.size == 1) { // Keep following the path queue.add(finder.copy(curr = next[0], distance = distance + 1)) } else { // We've either hit a fork or a dead-end, record the nodes addEdge(finder) queue.addAll(next.map { Edge(start = curr, curr = it, distance = 1) }) } } return Graph(edges, start, end) } private data class Graph(val edges: Map<Pos, Map<Pos, Int>>, val start: Pos, val end: Pos) private data class Edge(val start: Pos, val curr: Pos, val distance: Int) private data class Hike(val curr: Pos, val visited: Set<Pos>, val distance: Int = 0) private data class Pos(val x: Int, val y: Int) { fun move(direction: Direction) = when (direction) { Direction.NORTH -> copy(y = y - 1) Direction.EAST -> copy(x = x + 1) Direction.SOUTH -> copy(y = y + 1) Direction.WEST -> copy(x = x - 1) } } private enum class Direction { NORTH, EAST, SOUTH, WEST } private fun parse(input: String) = input.splitNewlines() }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
4,841
advent-of-code
MIT License
src/main/kotlin/leetcode/kotlin/dp/152. Maximum Product Subarray.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.dp /** 1. Optimal structure f(n) = Max( // max product till index n g`(n-1)*arr[n], // min product ending at index n-1 * arr[n] arr[n], // element at index n, single element product f`(n-1)*arr[n], // max product ending at index n-1 * arr[n] f(n-1) // max product found so far till index n-1 ) f`(n) = Max( // max product ending at index n f'(n-1) * arr[n], arr[n], g'(n-1) * arr[n] ) g`(n) = Min( // min product ending at index n f'(n-1) * arr[n], arr[n], g'(n-1) * arr[n] ) 2. sub-problems calls tree for f(4), depicting overlapping sub-problems same as (53. Maximum Subarray.kt) */ fun main() { println(maxProduct(intArrayOf(2, -5, -2, -4, 3))) } // dp, top-down // though StackOverFlow for big array size, works well for small lateinit var dpmax: IntArray lateinit var dpmin: IntArray private fun maxProduct(nums: IntArray): Int { dpmax = IntArray(nums.size) dpmin = IntArray(nums.size) var dp = IntArray(nums.size) fun maxproduct(n: Int): Int { if (n == 0) return nums[0] if (dp[n] == 0) { dp[n] = (maxproduct(n - 1)) .coerceAtLeast(minEndingAtIndex(n - 1, nums) * nums[n]) .coerceAtLeast(maxEndingAtIndex(n - 1, nums) * nums[n]) .coerceAtLeast(nums[n]) } return dp[n] } return maxproduct(nums.size - 1) } private fun maxEndingAtIndex(i: Int, nums: IntArray): Int { if (i == 0) return nums[0] if (dpmax[i] == 0) { dpmax[i] = nums[i].coerceAtLeast(maxEndingAtIndex(i - 1, nums) * nums[i]) .coerceAtLeast(minEndingAtIndex(i - 1, nums) * nums[i]) } return dpmax[i] } private fun minEndingAtIndex(i: Int, nums: IntArray): Int { if (i == 0) return nums[0] if (dpmin[i] == 0) { dpmin[i] = nums[i].coerceAtMost(maxEndingAtIndex(i - 1, nums) * nums[i]) .coerceAtMost(minEndingAtIndex(i - 1, nums) * nums[i]) } return dpmin[i] } // dp, bottom-up // f[i] means maximum product that can be achieved ending with i // g[i] means minimum product that can be achieved ending with i private fun maxProduct2(A: IntArray): Int { if (A.isEmpty()) return 0 val f = IntArray(A.size) val g = IntArray(A.size) f[0] = A[0] g[0] = A[0] var res: Int = A[0] for (i in 1 until A.size) { f[i] = (f[i - 1] * A[i]).coerceAtLeast(g[i - 1] * A[i]).coerceAtLeast(A[i]) g[i] = (f[i - 1] * A[i]).coerceAtMost(g[i - 1] * A[i]).coerceAtMost(A[i]) res = res.coerceAtLeast(f[i]) } return res }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
2,779
kotlinmaster
Apache License 2.0
src/Day03.kt
meierjan
572,860,548
false
{"Kotlin": 20066}
import java.lang.IllegalArgumentException data class RucksackContent( val first: String, val second: String ) { companion object { fun parse(text: String): RucksackContent { val middle = text.length / 2 return RucksackContent( first = text.substring(0, middle), second = text.substring(middle, text.length) ) } } } val Char.priority get() : Int = if (this in 'a'..'z') { this - 'a' + 1 } else if (this in 'A'..'z') { this - 'A' + 27 } else { throw IllegalArgumentException("Must be within a-z or A-Z") } fun String.countChars(): Map<Char, Int> { val result = LinkedHashMap<Char, Int>() for (entry in this) { val newVal = result.getOrDefault(entry, 0).inc() result[entry] = newVal } return result } fun day3_part1(input: List<String>): Int = input.map { RucksackContent.parse(it) } .map { rucksack -> val left = rucksack.first.countChars().mapValues { 1 } val right = rucksack.second.countChars().mapValues { 1 } left.filterKeys { right.containsKey(it) } } .map { it.map { it.key.priority }.sum() }.sum() fun day3_part2(input: List<String>): Int = input.chunked(3).map { val one = it[0].countChars() val two = it[1].countChars() val three = it[2].countChars() one.filterKeys { key -> two.containsKey(key) && three.containsKey(key) } }.sumOf { it.keys.sumOf { it.priority } } fun main() { // // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_1_test") println(day3_part1(testInput)) check(day3_part1(testInput) == 157) val input = readInput("Day03_1") println(day3_part1(input)) check(day3_part2(testInput) == 70) println(day3_part2(input)) }
0
Kotlin
0
0
a7e52209da6427bce8770cc7f458e8ee9548cc14
1,959
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/days/aoc2015/Day15.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2015 import days.Day class Day15: Day(2015, 15) { override fun partOne(): Any { val ingredients = inputList.map(::parseIngredients) val recipes = permuteRecipes(100, ingredients, null) return recipes.map { recipe -> recipe.contents.flatMap { (amount, ingredient) -> ingredient.attributes.mapNotNull { (propertyWeight, property) -> if (property != "calories") Pair(propertyWeight * amount, property) else null } } }.map { propertyList -> val tmp = propertyList.groupBy { it.second }.map { it.value.sumBy { propertyTotal -> propertyTotal.first } }.map { if (it < 0) 0 else it } tmp.reduce { acc, i -> acc * i } }.maxOrNull()!! } private fun permuteRecipes(capacityLeft: Int, ingredients: List<Ingredient>, currentRecipeSoFar: Recipe?): List<Recipe> { val recipes = mutableListOf<Recipe>() if (ingredients.size == 1) { if (capacityLeft > 0) { currentRecipeSoFar?.contents?.add(Pair(capacityLeft, ingredients[0])) } recipes.add(currentRecipeSoFar!!) } else { val ingredient = ingredients[0] for (i in capacityLeft downTo 0) { val recipe = Recipe(currentRecipeSoFar) if (i > 0) { recipe.contents.add(Pair(i, ingredient)) } recipes.addAll(permuteRecipes(capacityLeft - i, ingredients.drop(1), recipe)) } } return recipes } private tailrec fun sequenceRecipes(capacityLeft: Int, ingredients: List<Ingredient>, currentRecipeSoFar: Recipe?) = sequence { if (ingredients.size == 1) { if (capacityLeft > 0) { currentRecipeSoFar?.contents?.add(Pair(capacityLeft, ingredients[0])) } yield(currentRecipeSoFar!!) } else { val ingredient = ingredients[0] for (i in capacityLeft downTo 0) { val recipe = Recipe(currentRecipeSoFar) if (i > 0) { recipe.contents.add(Pair(i, ingredient)) } permuteRecipes(capacityLeft - i, ingredients.drop(1), recipe) } } } override fun partTwo(): Any { val ingredients = inputList.map(::parseIngredients) val recipes = permuteRecipes(100, ingredients, null) return recipes.map { recipe -> recipe.contents.flatMap { (amount, ingredient) -> ingredient.attributes.mapNotNull { (propertyWeight, property) -> Pair(propertyWeight * amount, property) } } }.map { propertyList -> val tmp = propertyList.groupBy { it.second }.map { Pair(it.key, it.value.sumBy { propertyTotal -> propertyTotal.first }) }.map { if (it.first == "calories") { if (it.second == 500) 1 else 0 } else { it.second } }.map { if (it < 0) 0 else it } tmp.reduce { acc, i -> acc * i } }.maxOrNull()!! } } fun parseIngredients(string: String): Ingredient { return Ingredient(string.substring(string.indexOf(':') + 2).split(", ").map { Regex("(\\w+) (-)?(\\d+)").matchEntire(it)?.destructured?.let { (attribute, sign, amount) -> Pair(if ("-" == sign) amount.toInt().unaryMinus() else amount.toInt(), attribute) }!! }) } class Ingredient(val attributes: List<Pair<Int, String>>) class Recipe { constructor(currentRecipeSoFar: Recipe?) { contents.addAll(currentRecipeSoFar?.contents ?: listOf()) } val contents = mutableListOf<Pair<Int,Ingredient>>() }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
4,077
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/y2023/day13/Day13.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day13 import util.InputReader typealias PuzzleInput = String class Day13(val input: PuzzleInput) { val maps = input.toPuzzleMaps() fun partOne(): Int { return maps.sumOf { it.score() } } fun partTwo(): Int { for (map in maps) { val y = map.yReflections().toSet() val x = map.xReflections().toSet() val firstDifference = map.smudgeOne().filter { smudged -> (smudged.yReflections().toSet() - y).isNotEmpty() || (smudged.xReflections().toSet() - x).isNotEmpty() }.toList() if (firstDifference.size != 1) { error("No difference found") } for (smudged in map.smudgeOne()) { if (smudged.score() == 0) { return smudged.chars.sumOf { line -> line.count { it == '#' } } } } } return -1 } } fun String.toPuzzleMaps(): List<PuzzleMap> { val chunks = this.split("\n\n") return chunks.map { it.toPuzzleMap() } } fun String.toPuzzleMap(): PuzzleMap { return PuzzleMap(this.trim().lines().map { it.toList() }) } data class PuzzleMap(val chars: List<List<Char>>) { override fun toString(): String { return chars.joinToString("\n") { it.joinToString("") } } } fun PuzzleMap.score(): Int { // To summarize your pattern notes, add up the number of columns to the left of each vertical line of reflection; // to that, also add 100 multiplied by the number of rows above each horizontal line of reflection. val yScore = yReflections().sumOf { it } val xScore = xReflections().sumOf { 100 * it } return yScore + xScore } private fun PuzzleMap.xReflections() = (1 until chars.size).mapNotNull { x -> if (reflectAboutX(x) == this) x else null } private fun PuzzleMap.yReflections() = (1 until chars.first().size).mapNotNull { y -> if (reflectAboutY(y) == this) y else null } fun PuzzleMap.reflectAboutY(y: Int): PuzzleMap { val newChars = chars.map { line -> line.reflectAbout(y) } return PuzzleMap(newChars) } fun PuzzleMap.reflectAboutX(x: Int): PuzzleMap { val newChars = chars.reflectAbout(x) return PuzzleMap(newChars) } fun <E> List<E>.reflectAbout(i: Int): List<E> { var (head, tail) = this.splitAt(i) tail = tail.toMutableList() head.reversed().forEachIndexed { at, item -> if (at < tail.size) { tail[at] = item } } return head + tail } private fun <E> List<E>.splitAt(y: Int): Pair<List<E>, List<E>> { val before = this.subList(0, y) val after = this.subList(y, this.size) return Pair(before, after) } private fun PuzzleMap.smudgeOne(): Sequence<PuzzleMap> = sequence { for (y in chars.indices) { for (x in chars.first().indices) { yield(smudge(y, x)) } } } fun PuzzleMap.smudge(y: Int, x: Int) = copy(chars = chars.smudge(y, x)) fun List<List<Char>>.smudge(y: Int, x: Int): List<List<Char>> { val result = this.toMutableList().map { it.toMutableList() } result[y][x] = if (result[y][x] == '.') '#' else '.' return result } fun main() { val year = 2023 val day = 13 val exampleInput: PuzzleInput = InputReader.getExample(year, day) val puzzleInput: PuzzleInput = InputReader.getPuzzle(year, day) fun partOne(input: PuzzleInput) = Day13(input).partOne() fun partTwo(input: PuzzleInput) = Day13(input).partTwo() println("Example 1: ${partOne(exampleInput)}") println("Puzzle 1: ${partOne(puzzleInput)}") println("Example 2: ${partTwo(exampleInput)}") }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
3,663
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-11.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import com.github.ferinagy.adventOfCode.readInputText fun main() { val input = readInputText(2022, "11-input") val testInput1 = readInputText(2022, "11-test1") println("Part1:") part1(testInput1).println() part1(input).println() println() println("Part2:") part2(testInput1).println() part2(input).println() } private fun part1(input: String): Long { return solve(input, 20, reducer = { it / 3 }) } private fun part2(input: String): Long { return solve(input, 10000, reducer = { it }) } private fun solve(input: String, n: Int, reducer: (Long) -> Long): Long { val monkeys = monkeys(input) val max = monkeys.map { it.test }.reduce(Long::times) val counts = LongArray(monkeys.size) repeat(n) { monkeys.forEachIndexed { index, monkey -> while (monkey.items.isNotEmpty()) { var current = monkey.items.removeFirst() current = monkey.operation(current) current = reducer(current) current %= max counts[index]++ if (current % monkey.test == 0L) { monkeys[monkey.ifTrue].items += current } else { monkeys[monkey.ifFalse].items += current } } } } return counts.sortedDescending().take(2).let { it[0] * it[1] } } fun parseOp(s: String): (Long) -> Long { val regex = """ Operation: new = old ([*+]) (\d+|old)""".toRegex() val (op, value) = regex.matchEntire(s)!!.destructured val op2: Long.(Long)->Long = if (op == "*") Long::times else Long::plus return { it.op2(value.toLongOrNull() ?: it) } } fun parseTest(s: String): Long { require(s.startsWith(" Test: divisible by ")) return s.substring(21).toLong() } private fun monkeys(input: String): List<Monkey> { val monkeys = input.split("\n\n").map { config -> val lines = config.lines() Monkey( items = lines[1].substring(18).split(", ").map { it.toLong() }.toMutableList(), operation = parseOp(lines[2]), test = parseTest(lines[3]), ifTrue = lines[4].substring(29).toInt(), ifFalse = lines[5].substring(30).toInt(), ) } return monkeys } private data class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, val test: Long, val ifTrue: Int, val ifFalse: Int )
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,604
advent-of-code
MIT License
src/main/kotlin/io/github/aarjavp/aoc/day09/Day09.kt
AarjavP
433,672,017
false
{"Kotlin": 73104}
package io.github.aarjavp.aoc.day09 import io.github.aarjavp.aoc.readFromClasspath class Day09 { class Grid(val lines: List<String>) { data class Location(val row: Int, val column: Int) operator fun get(row: Int, column: Int): Char? = lines.getOrNull(row)?.getOrNull(column) operator fun get(row: Int, column: Int, direction: Direction): Char? { return get(row + direction.rowOffset, column + direction.columnOffset) } //Note: assumes the location exists on the grid operator fun get(location: Location): Char = lines[location.row][location.column] operator fun Location.get(direction: Direction): Location? { val neighbor = Location(row + direction.rowOffset, column + direction.columnOffset) return neighbor.takeIf { get(neighbor.row, neighbor.column) != null } } fun findLowPoints(): List<Location> { val directionsToCheck = Direction.values() val lowPoints = mutableListOf<Location>() for ((row, line) in lines.withIndex()) { candidateCheck@ for (column in line.indices) { val candidate = line[column] for (direction in directionsToCheck) { val neighbor = get(row, column, direction) ?: continue if (candidate >= neighbor) continue@candidateCheck } lowPoints.add(Location(row = row, column = column)) } } return lowPoints } fun findBasins(seeds: List<Location>): List<Set<Location>> { val directionsToCheck = Direction.values() val basins = mutableListOf<Set<Location>>() for (seed in seeds) { if (basins.any { seed in it }) continue val visited = mutableSetOf<Location>() val toCheck = mutableListOf(seed) val currentBasin = mutableSetOf(seed) while (toCheck.isNotEmpty()) { val current = toCheck.removeFirst() visited += current for (direction in directionsToCheck) { val neighbor = current[direction] ?: continue if (neighbor in visited || this[neighbor] == '9') continue currentBasin += neighbor toCheck += neighbor } } basins += currentBasin } return basins } } enum class Direction(val rowOffset: Int = 0, val columnOffset: Int = 0) { UP(rowOffset = -1), DOWN(rowOffset = 1), LEFT(columnOffset = -1), RIGHT(columnOffset = 1) } fun part1(grid: Grid): Int { val lowPoints = grid.findLowPoints() val risks = lowPoints.map { grid[it].digitToInt() + 1 } return risks.sum() } fun part2(grid: Grid): Int { val basins = grid.findBasins(grid.findLowPoints()) return basins.sortedByDescending { it.size }.take(3).fold(1) { p, basin -> p * basin.size } } } fun main() { val solution = Day09() readFromClasspath("Day09.txt").useLines { lines -> val grid = Day09.Grid(lines.toList()) val sumOfRisks = solution.part1(grid) println(sumOfRisks) val magicNumber = solution.part2(grid) println(magicNumber) } }
0
Kotlin
0
0
3f5908fa4991f9b21bb7e3428a359b218fad2a35
3,449
advent-of-code-2021
MIT License
src/day11/Day11.kt
banshay
572,450,866
false
{"Kotlin": 33644}
package day11 import day05.splitAtEmpty import readInput fun main() { fun part1(input: List<String>): Long { val monkeys = input.parseMonkeys() for (round in 0 until 20) { monkeys.mapValues { it.value.inspect() } } return monkeys.map { it.value.inspectCount } .sorted() .takeLast(2) .reduce { left, right -> left * right } } fun part2(input: List<String>): Long { val monkeys = input.parseMonkeys() val base = monkeys.values.fold(1L) { acc, it -> acc * it.testNumber } for (round in 1..10_000) { monkeys.mapValues { it.value.inspect2(base) } } return monkeys.map { it.value.inspectCount } .sorted() .takeLast(2) .reduce { left, right -> left * right } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") val input = readInput("Day11") println("test part1: ${part1(testInput)}") println("result part1: ${part1(input)}") println("test part2: ${part2(testInput)}") println("result part2: ${part2(input)}") } fun Map<Int, Monkey>.prettyPrint(round: Int) { println("== After round $round ==") this.forEach { println("Monkey ${it.key}: ${it.value.inspectCount}") } println() } data class Monkey(val items: MutableList<Long>, val testNumber: Int, val operation: (Long) -> Long, val test: (Long) -> Monkey) { var inspectCount = 0L fun inspect() { inspectCount += items.size items.map { operation(it) } .map { it.floorDiv(3) } .forEach { test(it).items.add(it) } items.clear() } fun inspect2(base: Long) { inspectCount += items.size items.map { operation(it) } .map { it.mod(base) } .forEach { test(it).items.add(it) } items.clear() } } fun List<String>.parseMonkeys(): Map<Int, Monkey> { val monkeys = mutableMapOf<Int, Monkey>() this.splitAtEmpty() .map { monkeyDef -> val (key) = Regex("""(\d+)""").find(monkeyDef[0])!!.destructured val items = Regex("""(\d+)+""").findAll(monkeyDef[1]).map { match -> match.groupValues[1] }.toList().map { it.toLong() }.toMutableList() val (operand, rhs) = Regex("""Operation: new = old ([+\-*]) (\d+|old)""").find(monkeyDef[2])!!.destructured val test = Regex("""Test: divisible by (\d+)""").find(monkeyDef[3])!!.destructured.component1().toInt() val (truthyMonkey) = Regex("""If true: throw to monkey (\d+)""").find(monkeyDef[4])!!.destructured val (faultyMonkey) = Regex("""If false: throw to monkey (\d+)""").find(monkeyDef[5])!!.destructured key.toInt() to Monkey(items, test, { when (operand) { "+" -> it + parseRightHandSide(it, rhs) "-" -> it - parseRightHandSide(it, rhs) else -> it * parseRightHandSide(it, rhs) } }) { when (it % test) { 0L -> monkeys[truthyMonkey.toInt()]!! else -> monkeys[faultyMonkey.toInt()]!! } } } .forEach { monkeys[it.first] = it.second } return monkeys } fun parseRightHandSide(old: Long, rhs: String) = when (rhs) { "old" -> old else -> rhs.toLong() }
0
Kotlin
0
0
c3de3641c20c8c2598359e7aae3051d6d7582e7e
3,518
advent-of-code-22
Apache License 2.0
src/commonMain/kotlin/advent2020/day11/Day11Puzzle.kt
jakubgwozdz
312,526,719
false
null
package advent2020.day11 import advent2020.utils.atLeast import kotlin.time.TimeSource.Monotonic val directions by lazy { (-1..1).flatMap { dr -> (-1..1).map { dc -> (dr to dc) as Pos } } - (0 to 0) } typealias Vector = Pair<Int, Int> typealias Pos = Pair<Int, Int> operator fun Pos.plus(v: Vector): Pos = first + v.first to second + v.second data class Area( private val lines: List<String>, ) { constructor(input: String) : this(input.trim().lines()) val rows: Int = lines.size val cols: Int = lines[0].length val seats = seats(lines) val size = rows * cols fun occupied(index: Int) = lines[index / cols][index % cols] == '#' operator fun contains(p: Pos) = p.first in lines.indices && p.second in lines[0].indices } private fun seats(lines: List<String>) = lines.flatMapIndexed { row, line -> line.mapIndexedNotNull { column, c -> val pos: Pos = row to column when (c) { '#' -> pos 'L' -> pos else -> null } } }.toHashSet() fun part1(input: String): String { val area = Area(input) val seatsWithNeighbours = area.seats.map { pos -> val neighbours = directions.mapNotNull { v -> val p = pos + v if (p in area.seats) return@mapNotNull p else return@mapNotNull null } pos to neighbours } return common(area, seatsWithNeighbours, 4).toString() } fun part2(input: String): String { val area = Area(input) val seatsWithNeighbours = area.seats.map { pos -> val neighbours = directions.mapNotNull { v -> var p = pos + v while (p in area) if (p in area.seats) return@mapNotNull p else p += v return@mapNotNull null } pos to neighbours } return common(area, seatsWithNeighbours, 5).toString() } fun common(area: Area, seatsWithNeighbours: List<Pair<Pos, List<Pos>>>, leaveThreshold: Int): Int { val s = Monotonic.markNow() val cols = area.cols val even = BooleanArray(area.rows * cols, area::occupied) val odd = BooleanArray(area.rows * cols, area::occupied) var count = 0 // println("$count: ${s.elapsedNow()}") while (true) { val (src, dest) = if (count % 2 == 0) even to odd else odd to even val occupied = { pos: Pos -> src[pos.first * cols + pos.second] } seatsWithNeighbours.forEach { (pos, list) -> dest[pos.first * cols + pos.second] = when (occupied(pos)) { true -> !list.atLeast(leaveThreshold, occupied) false -> list.none(occupied) } } count++ // println("$count: ${s.elapsedNow()}") if (even.contentEquals(odd)) { return seatsWithNeighbours.count { (pos, _) -> dest[pos.first * cols + pos.second] } } } }
0
Kotlin
0
2
e233824109515fc4a667ad03e32de630d936838e
2,828
advent-of-code-2020
MIT License
src/Day03.kt
mikemac42
573,071,179
false
{"Kotlin": 45264}
/** * Each rucksack has 2 compartments with same number of items. Each line represents all items in a rucksack. * Elf that did the packing failed to follow this rule for exactly one item type per rucksack. * Every item type is identified by a single lowercase or uppercase letter. * Lowercase item types a through z have priorities 1 through 26. * Uppercase item types A through Z have priorities 27 through 52. */ fun sumPrioritiesPart1(input: String): Int = input.lines().sumOf { it.toRucksack().commonItem().priority() } /** * Each group of 3 lines is an Elf group. * The badge is the item type carried by all three Elves in a group. */ fun sumPrioritiesPart2(input: String): Int = input.lines().map { it.toList() }.chunked(3).sumOf { commonItem(it).priority() } data class Rucksack(val leftCompartment: List<Char>, val rightCompartment: List<Char>) { fun commonItem(): Char = commonItem(listOf(leftCompartment, rightCompartment)) } fun String.toRucksack(): Rucksack = Rucksack( subSequence(0, length / 2).toList(), subSequence(length / 2, length).toList() ) fun commonItem(charLists: List<List<Char>>): Char { val searchList = charLists.first() val otherLists = charLists.subList(1, charLists.size) searchList.forEach { item -> if (otherLists.all { it.contains(item) }) { return item } } throw IllegalStateException() } fun Char.priority(): Int = if (this.isLowerCase()) { this.code - 96 } else { this.code - 38 }
0
Kotlin
1
0
909b245e4a0a440e1e45b4ecdc719c15f77719ab
1,492
advent-of-code-2022
Apache License 2.0
src/Day07.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
private class Solution07(input: List<String>) { private val root = Node("/") init { var currentNode = root input.forEach {line -> when (line.substring(0, 4).trim()) { "$ cd" -> currentNode = when (val dirname = line.substring(4).trim()) { "/" -> root ".." -> currentNode.parent!! else -> currentNode.children.first { it.id == dirname } } "dir" -> { val dirname = line.substring(4) currentNode.children.add(Node(dirname, parent = currentNode)) } else -> { val split = line.split(" ") val size = split[0].toIntOrNull() if (size != null ) { val filename = split[1] currentNode.children.add(Node(filename, parent = currentNode, _size = size)) } } } } } private data class Node(val id: String, private var _size: Int? = null, val parent: Node? = null) { val children: MutableList<Node> = mutableListOf() val size: Int get() { if (_size == null) _size = children.sumOf { it.size } return _size!! } val allChildren: List<Node> get() { val allChildren = mutableListOf(this) allChildren.addAll(children.flatMap { it.allChildren }) return allChildren } val isNoLeaf: Boolean get() = children.isNotEmpty() } fun part1() = root.allChildren.filter { it.isNoLeaf }.filter { it.size <= 100000 }.sumOf { it.size } fun part2() = root.allChildren.filter { it.isNoLeaf }.filter { it.size >= root.size - 40000000 }.minOf { it.size } } fun main() { val testSolution = Solution07(readInput("Day07_test")) check(testSolution.part1() == 95437) check(testSolution.part2() == 24933642) val solution = Solution07(readInput("Day07")) println(solution.part1()) println(solution.part2()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
2,171
aoc-2022
Apache License 2.0
kotlin/src/2022/Day12_2022.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
import java.util.ArrayDeque private fun height(chr: Char) = when (chr) { 'S' -> 0 'E' -> 25 else -> chr - 'a' } private fun neighbors(y: Int, x: Int, yMax: Int, xMax: Int): List<Pair<Int, Int>> = listOf(y to x - 1, y to x + 1, y - 1 to x, y + 1 to x) .filter {it.first >= 0 && it.second >= 0 && it.first < yMax && it.second < xMax} private fun findDist(start: List<Pair<Int, Int>>, M: List<List<Int>>, target: Pair<Int, Int>): Int { val q = ArrayDeque(start) val D = Array(M.size) {Array(M[0].size) {-1} } for (p in start) D[p.first][p.second] = 0 while (q.isNotEmpty()) { val p = q.removeLast() for (tar in neighbors(p.first, p.second, M.size, M[0].size)) { if (M[tar.first][tar.second] > M[p.first][p.second] + 1) continue if (D[tar.first][tar.second] >= 0) continue q.addFirst(tar) D[tar.first][tar.second] = D[p.first][p.second] + 1 } } return D[target.first][target.second] } fun main() { val input = readInput(12).trim().lines() val M = input.map { it.toList().map(::height) } fun posOf(chr: Char): Pair<Int, Int> { for (y in M.indices) for (x in M[0].indices) if (input[y][x] == chr) return y to x return -1 to -1 } // part1 val start1 = listOf(posOf('S')) val target = posOf('E') println(findDist(start1, M, target)) // part2 val start2 = mutableListOf<Pair<Int, Int>>() for (y in M.indices) for (x in M[0].indices) if (M[y][x] == 0) start2.add(y to x) println(findDist(start2, M, target)) }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
1,659
adventofcode
Apache License 2.0
src/Day02.kt
treegem
572,875,670
false
{"Kotlin": 38876}
import Move.* import Outcome.* import common.readInput val possibleMovesNumber = Move.values().size fun main() { val day = "02" fun part1(input: List<String>) = input.sumOf { calculateScorePart1(it) } fun part2(input: List<String>) = input.sumOf { calculateScorePart2(it) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) } private enum class Move(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3), } private enum class Outcome(val score: Int) { WIN(6), DRAW(3), LOSS(0), } private fun getMyMovePart1(line: String) = when (line.last()) { 'X' -> ROCK 'Y' -> PAPER 'Z' -> SCISSORS else -> throw IllegalArgumentException(line) } private fun getOpponentMove(line: String) = when (line.first()) { 'A' -> ROCK 'B' -> PAPER 'C' -> SCISSORS else -> throw IllegalArgumentException(line) } private fun calculateOutcomePart1(myMove: Move, opponentMove: Move) = when (myMove.ordinal) { (opponentMove.ordinal + 1) % possibleMovesNumber -> WIN opponentMove.ordinal -> DRAW else -> LOSS } private fun getOutcomePart2(line: String) = when (line.last()) { 'X' -> LOSS 'Y' -> DRAW 'Z' -> WIN else -> throw IllegalArgumentException(line) } private fun calculateScorePart1(line: String): Int { val myMove = getMyMovePart1(line) val opponentMove = getOpponentMove(line) val outcome = calculateOutcomePart1(myMove, opponentMove) return myMove.score + outcome.score } private fun calculateMyMovePart2(opponentMove: Move, outcome: Outcome) = when (outcome) { WIN -> Move.values()[(opponentMove.ordinal + 1) % possibleMovesNumber] DRAW -> opponentMove LOSS -> Move.values()[(opponentMove.ordinal + 2) % possibleMovesNumber] } private fun calculateScorePart2(line: String): Int { val opponentMove = getOpponentMove(line) val outcome = getOutcomePart2(line) val myMove: Move = calculateMyMovePart2(opponentMove, outcome) return myMove.score + outcome.score }
0
Kotlin
0
0
97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8
2,222
advent_of_code_2022
Apache License 2.0
src/day9/Day9.kt
davidcurrie
579,636,994
false
{"Kotlin": 52697}
package day9 import java.io.File import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sign fun main() { val input = File("src/day9/input.txt").readLines() .map { line -> line.split(" ") } .map { parts -> Pair(parts[0], parts[1].toInt()) } .toList() println(solve(input, 2)) println(solve(input, 10)) } fun solve(input: List<Pair<String, Int>>, knots: Int): Int { val rope = MutableList(knots) { Pair(0, 0) } val visited = mutableSetOf<Pair<Int, Int>>() visited.add(rope.last()) val deltas = mapOf("U" to Pair(0, 1), "D" to Pair(0, -1), "L" to Pair(-1, 0), "R" to Pair(1, 0)) input.forEach { pair -> for (i in 1..pair.second) { val delta = deltas[pair.first]!! rope[0] = Pair(rope[0].first + delta.first, rope[0].second + delta.second) for (j in 1 until knots) { if (abs(rope[j - 1].second - rope[j].second) == 2 || abs(rope[j - 1].first - rope[j].first) == 2) { rope[j] = Pair( rope[j].first + sign(rope[j - 1].first - rope[j].first), rope[j].second + sign(rope[j - 1].second - rope[j].second) ) } } visited.add(rope.last()) } } return visited.size } fun sign(input: Int): Int { return sign(input.toDouble()).toInt() } fun outputRope(rope: MutableList<Pair<Int, Int>>) { for (j in max(0, rope.maxOf { it.second }) downTo min(0, rope.minOf { it.second })) { for (i in min(0, rope.minOf { it.first })..max(0, rope.maxOf { it.first })) { var output = "." if (i == 0 && j == 0) { output = "s" } for (k in rope.indices) { if (i == rope[k].first && j == rope[k].second) { output = when (k) { 0 -> "H" rope.size - 1 -> "T" else -> k.toString() } break } } print(output) } println() } println() }
0
Kotlin
0
0
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
2,217
advent-of-code-2022
MIT License
src/2022/Day05.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput import splitBy fun main() { fun readStackChart(stackChart: List<String>): List<MutableList<Char>> { val cargoStacks = stackChart.last().trim().split("\\s+".toRegex()).map { _ -> mutableListOf<Char>() } for (i in 0..(stackChart.size - 2)) { cargoStacks.forEachIndexed { index, stack -> val charIndex = index * 4 + 1 val stackLevel = stackChart[i] if (stackLevel.length <= charIndex || stackLevel[charIndex] == ' ') return@forEachIndexed stack.add(stackLevel[charIndex]) } } return cargoStacks } fun prepareInput(input: List<String>): StacksAndCommands { val (stackChart, commandDescriptions) = input.splitBy { it.isEmpty() } return StacksAndCommands( readStackChart(stackChart), commandDescriptions.map(Command.Companion::fromDescription) ) } fun part1(input: List<String>): String { val (stacks, commands) = prepareInput(input) val rearrangedStacks = commands.fold(stacks) { next, command -> command.executeCommand(next, Mover.CrateMover9000) } return rearrangedStacks.map { it.first() }.joinToString("") } fun part2(input: List<String>): String { val (stacks, commands) = prepareInput(input) val rearrangedStacks = commands.fold(stacks) { next, command -> command.executeCommand(next, Mover.CrateMover9001) } return rearrangedStacks.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)) } data class StacksAndCommands( val stacks: List<MutableList<Char>>, val commands: List<Command>, ) data class Command( val to: Int, val from: Int, val count: Int, ) { companion object { private operator fun <E> List<E>.component6(): E { return this[5] } fun fromDescription(description: String): Command { val (_, count, _, from, _, to) = description.split(" ") return Command( to = to.toInt() - 1, from = from.toInt() - 1, count = count.toInt(), ) } } } sealed interface Mover { fun move(from: MutableList<Char>, to: MutableList<Char>, count: Int) object CrateMover9000: Mover { override fun move(from: MutableList<Char>, to: MutableList<Char>, count: Int) { for (i in 0 until count) { to.add(0, from.first()) from.removeFirst() } } } object CrateMover9001: Mover { override fun move(from: MutableList<Char>, to: MutableList<Char>, count: Int) { val (cargos) = from.chunked(count) to.addAll(0, cargos) cargos.forEach { _ -> from.removeFirst()} } } } fun Command.executeCommand(stacks: List<MutableList<Char>>, mover: Mover): List<MutableList<Char>> { mover.move(stacks[from], stacks[to], count) return stacks }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
3,308
aoc-2022-in-kotlin
Apache License 2.0
src/Day22.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
import java.lang.Exception import kotlin.math.abs data class Position(val x: Int, val y: Int, val type: Boolean) { val neighbors = mutableListOf<Position?>(null, null, null, null) fun neighborByDirection(direction: Int): Position = neighbors[(direction % 4 + 4) % 4]!! } fun main() { fun part1(inputFirst: List<String>): Int { val map = mutableSetOf<Position>() val index = inputFirst.indexOfFirst { it.isBlank() } val max = inputFirst.subList(0, index).maxOf { it.length } val input = inputFirst.mapIndexed { i, s -> if (i >= index) s else { s.padEnd(max, ' ') } } for (y in 0 until index) { for (x in 0..input[y].lastIndex) { if (input[y][x] != ' ') { map.add(Position(x, y, input[y][x] != '#')) } } } for (point in map) { if (point.x > 0 && input[point.y][point.x - 1] != ' ') point.neighbors[2] = Position(point.x - 1, point.y, input[point.y][point.x - 1] != '#') if (point.x < input[point.y].lastIndex && input[point.y][point.x + 1] != ' ') point.neighbors[0] = Position(point.x + 1, point.y, input[point.y][point.x + 1] != '#') if (point.y > 0 && input[point.y - 1][point.x] != ' ') point.neighbors[3] = Position(point.x, point.y - 1, input[point.y - 1][point.x] != '#') if (point.y < index - 1 && input[point.y + 1][point.x] != ' ') point.neighbors[1] = Position(point.x, point.y + 1, input[point.y + 1][point.x] != '#') } for (y in 0 until index) { val first = input[y].indexOfFirst { it != ' ' } val last = input[y].indexOfLast { it != ' ' } map.find { it.y == y && it.x == first }!!.neighbors[2] = Position(last, y, input[y][last] != '#') map.find { it.y == y && it.x == last }!!.neighbors[0] = Position(first, y, input[y][first] != '#') } for (x in 0 until max) { val filter = map.filter { it.x == x } val first = filter.minOf { it.y } val last = filter.maxOf { it.y } map.find { it.x == x && it.y == last }!!.neighbors[1] = Position(x, first, input[first][x] != '#') map.find { it.x == x && it.y == first }!!.neighbors[3] = Position(x, last, input[last][x] != '#') } val moves = input[index + 1] + " " var direction = 0 var currentPosition = map.filter { it.y == 0 }.toList().sortedBy { it.x }[0] val current = StringBuilder("") moves.forEach { if (it == 'R' || it == 'L' || it == ' ') { val times = current.toString().toInt() current.clear() repeat(times) { val nextPosition = currentPosition.neighborByDirection(direction) if (nextPosition.type) currentPosition = map.find { position -> position.x == nextPosition.x && position.y == nextPosition.y }!! else return@repeat } if (it == 'R') direction++ else if (it == 'L') direction-- } else { current.append(it) } } return 1000 * (currentPosition.y + 1) + 4 * (currentPosition.x + 1) + ((direction % 4 + 4) % 4) } fun part2(inputFirst: List<String>): Int { val map = mutableSetOf<Position>() val index = inputFirst.indexOfFirst { it.isBlank() } val max = inputFirst.subList(0, index).maxOf { it.length } val input = inputFirst.mapIndexed { i, s -> if (i >= index) s else { s.padEnd(max, ' ') } } for (y in 0 until index) { for (x in 0..input[y].lastIndex) { if (input[y][x] != ' ') { map.add(Position(x, y, input[y][x] != '#')) } } } for (point in map) { if (point.x > 0 && input[point.y][point.x - 1] != ' ') point.neighbors[2] = Position(point.x - 1, point.y, input[point.y][point.x - 1] != '#') if (point.x < input[point.y].lastIndex && input[point.y][point.x + 1] != ' ') point.neighbors[0] = Position(point.x + 1, point.y, input[point.y][point.x + 1] != '#') if (point.y > 0 && input[point.y - 1][point.x] != ' ') point.neighbors[3] = Position(point.x, point.y - 1, input[point.y - 1][point.x] != '#') if (point.y < index - 1 && input[point.y + 1][point.x] != ' ') point.neighbors[1] = Position(point.x, point.y + 1, input[point.y + 1][point.x] != '#') } // for (y in 0 until index) { // val first = input[y].indexOfFirst { it != ' ' } // val last = input[y].indexOfLast { it != ' ' } // map.find { it.y == y && it.x == first }!!.neighbors[2] = Position(last, y, input[y][last] != '#') // map.find { it.y == y && it.x == last }!!.neighbors[0] = Position(first, y, input[y][first] != '#') // } // // for (x in 0 until max) { // val filter = map.filter { it.x == x } // val first = filter.minOf { it.y } // val last = filter.maxOf { it.y } // map.find { it.x == x && it.y == last }!!.neighbors[1] = Position(x, first, input[first][x] != '#') // map.find { it.x == x && it.y == first }!!.neighbors[3] = Position(x, last, input[last][x] != '#') // } for (i in 0..49) { //1-3 map.find { it.x == i + 100 && it.y == 49 }!!.neighbors[1] = Position(99, 50 + i, input[50 + i][99] != '#') map.find { it.x == 99 && it.y == 50 + i }!!.neighbors[0] = Position(i + 100, 49, input[49][i + 100] != '#') //1-4 map.find { it.x == 149 && it.y == i }!!.neighbors[0] = Position(99, 149 - i, input[149 - i][99] != '#') map.find { it.x == 99 && it.y == 149 - i }!!.neighbors[0] = Position(149, i, input[i][149] != '#') //3-5 map.find { it.x == i && it.y == 100 }!!.neighbors[3] = Position(50, 50 + i, input[50 + i][50] != '#') map.find { it.x == 50 && it.y == 50 + i }!!.neighbors[2] = Position(i, 100, input[100][i] != '#') //2-5 map.find { it.x == 0 && it.y == 100 + i }!!.neighbors[2] = Position(50, 49 - i, input[49 - i][50] != '#') map.find { it.x == 50 && it.y == 49 - i }!!.neighbors[2] = Position(0, 100 + i, input[100 + i][0] != '#') // 1-6 map.find { it.x == 100 + i && it.y == 0 }!!.neighbors[3] = Position(i, 199, input[199][i] != '#') map.find { it.x == i && it.y == 199 }!!.neighbors[1] = Position(100 + i, 0, input[0][100 + i] != '#') //2-6 map.find { it.x == 50 + i && it.y == 0 }!!.neighbors[3] = Position(0, 150 + i, input[150 + i][0] != '#') map.find { it.x == 0 && it.y == 150 + i }!!.neighbors[2] = Position(50 + i, 0, input[0][50 + i] != '#') //4-6 map.find { it.x == 49 && it.y == 150 + i }!!.neighbors[0] = Position(50 + i, 149, input[149][50 + i] != '#') map.find { it.x == 50 + i && it.y == 149 }!!.neighbors[1] = Position(49, 150 + i, input[150 + i][49] != '#') } val moves = input[index + 1] + " " var direction = 0 var currentPosition = map.filter { it.y == 0 }.toList().sortedBy { it.x }[0] val current = StringBuilder("") moves.forEach { if (it == 'R' || it == 'L' || it == ' ') { val times = current.toString().toInt() current.clear() repeat(times) { val nextPosition = currentPosition.neighborByDirection(direction) if (nextPosition.type) currentPosition = map.find { position -> position.x == nextPosition.x && position.y == nextPosition.y }!! else return@repeat } if (it == 'R') direction++ else if (it == 'L') direction-- } else { current.append(it) } } return 1000 * (currentPosition.y + 1) + 4 * (currentPosition.x + 1) + ((direction % 4 + 4) % 4) } val input = readInput("Day22") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
8,585
Advent-of-code
Apache License 2.0
src/Day14/Day14.kt
martin3398
436,014,815
false
{"Kotlin": 63436, "Python": 5921}
fun main() { fun preprocess(input: List<String>): Pair<String, Map<String, String>> { val rules = input.slice(2 until input.size).associate { val split = it.split(" -> ") split[0] to split[1] } return Pair(input[0], rules) } fun init( input: String, rules: Map<String, String> ): Triple<Map<String, List<String>>, Map<String, Long>, MutableMap<String, Long>> { val rulesProcessed = mutableMapOf<String, List<String>>() val counts = mutableMapOf<String, Long>() for ((k, v) in rules.entries) { val l = listOf(k[0] + v, v + k[1]) rulesProcessed[k] = l counts[v] = 0L counts[k[0].toString()] = 0L counts[k[1].toString()] = 0L } counts[input[0].toString()] = 1 val inputProcessed = mutableMapOf<String, Long>() for (i in 1 until input.length) { val needle = input[i - 1].toString() + input[i].toString() inputProcessed[needle] = inputProcessed.getOrDefault(needle, 0L) + 1L counts[input[i].toString()] = counts.getOrDefault(input[i].toString(), 0) + 1 } return Triple(rulesProcessed, inputProcessed, counts) } fun step( inputProcessed: Map<String, Long>, rules: Map<String, String>, rulesProcessed: Map<String, List<String>>, counts: MutableMap<String, Long> ): Map<String, Long> { val inputProcessedNext = mutableMapOf<String, Long>() for ((k, l) in inputProcessed.entries) { rulesProcessed[k]?.forEach { inputProcessedNext[it] = inputProcessedNext.getOrDefault(it, 0L) + l } val added = rules[k] if (added != null) { counts[added] = counts.getOrDefault(added, 0) + l } } return inputProcessedNext } fun part1(input: String, rules: Map<String, String>): Long { var (rulesProcessed, inputProcessed, counts) = init(input, rules) for (i in 0 until 10) { inputProcessed = step(inputProcessed, rules, rulesProcessed, counts) } return counts.maxOf { it.value } - counts.minOf { it.value } } fun part2(input: String, rules: Map<String, String>): Long { var (rulesProcessed, inputProcessed, counts) = init(input, rules) for (i in 0 until 40) { inputProcessed = step(inputProcessed, rules, rulesProcessed, counts) } return counts.maxOf { it.value } - counts.minOf { it.value } } val (testInput, testRules) = preprocess(readInput(14, true)) val (input, rules) = preprocess(readInput(14)) check(part1(testInput, testRules) == 1588L) println(part1(input, rules)) check(part2(testInput, testRules) == 2188189693529) println(part2(input, rules)) }
0
Kotlin
0
0
085b1f2995e13233ade9cbde9cd506cafe64e1b5
2,889
advent-of-code-2021
Apache License 2.0
src/main/kotlin/aoc2023/Day04.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2023 import aoc2022.parsedBy import utils.InputUtils class Card(val id: Int, val winners: Set<Int>, val contents: Set<Int>) { fun matches() = winners.intersect(contents) fun score(): Int { val power = matches().size return if (power > 0) { 1 shl (power -1) } else 0 } } fun String.listOfNumbers(): List<Int> = trim().split(" +".toRegex()).map { it.trim().toInt() } fun String.setOfNumbers(): Set<Int> = listOfNumbers().toSet() fun String.parseCard(): Card = parsedBy("Card +(\\d+): (.*) \\| (.*)".toRegex()) { val (idStr, w, c) = it.destructured Card(idStr.toInt(), w.setOfNumbers(), c.setOfNumbers()) } fun main() { val testInput = """Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11""".trimIndent().split("\n") fun part1(input: List<String>): Int { return input.sumOf { it.parseCard().score() } } fun part2(input: List<String>): Int { val copies = IntArray(input.size + 1) { if(it>0) { 1 } else{0}} input.map { it.parseCard() } .forEach { card -> val matches = card.matches().size val score = copies[card.id] (1..matches).forEach { i -> copies[card.id+i] += score } } return copies.sum() } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 13) println(part2(testInput)) val puzzleInput = InputUtils.downloadAndGetLines(2023, 4) val input = puzzleInput.toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
1,878
aoc-2022-kotlin
Apache License 2.0
src/Day02.kt
faragogergo
573,451,927
false
{"Kotlin": 4406}
fun main() { fun part1(input: List<String>): Int { val scores = mapOf( Pair("A", "X") to 1 + 3, Pair("A", "Y") to 2 + 6, Pair("A", "Z") to 3 + 0, Pair("B", "X") to 1 + 0, Pair("B", "Y") to 2 + 3, Pair("B", "Z") to 3 + 6, Pair("C", "X") to 1 + 6, Pair("C", "Y") to 2 + 0, Pair("C", "Z") to 3 + 3, ) return input.sumOf { row -> row.split(" ") .let { scores.getValue(Pair(it[0], it[1])) } } } fun part2(input: List<String>): Int { val scores = mapOf( Pair("A", "X") to 3 + 0, Pair("A", "Y") to 1 + 3, Pair("A", "Z") to 2 + 6, Pair("B", "X") to 1 + 0, Pair("B", "Y") to 2 + 3, Pair("B", "Z") to 3 + 6, Pair("C", "X") to 2 + 0, Pair("C", "Y") to 3 + 3, Pair("C", "Z") to 1 + 6, ) return input.sumOf { row -> row.split(" ") .let { scores.getValue(Pair(it[0], it[1])) } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
47dce5333f3c3e74d02ac3aaf51501069ff615bc
1,434
Advent_of_Code_2022
Apache License 2.0
src/Day02.kt
jamesrobert
573,249,440
false
{"Kotlin": 13069}
enum class Outcome(val value: String) { Lose("X"), Draw("Y"), Win("Z"); companion object { fun parse(input: String): Outcome = when (input) { "X" -> Lose "Y" -> Draw "Z" -> Win else -> error("incorrect outcome") } } } enum class RockPaperScissors(val value: Int) { Rock(1), Paper(2), Scissors(3); fun fight(opponent: RockPaperScissors): Int = when { this == opponent -> 3 (this == Rock && opponent == Scissors) || (this == Paper && opponent == Rock) || (this == Scissors && opponent == Paper) -> 6 else -> 0 } companion object { fun parse(input: String): RockPaperScissors = when (input) { "X", "A" -> Rock "Y", "B" -> Paper "Z", "C" -> Scissors else -> error("invalid choice") } fun parse(outcome: Outcome, opponent: RockPaperScissors): RockPaperScissors { return when (opponent to outcome) { Rock to Outcome.Win -> Paper Rock to Outcome.Lose -> Scissors Paper to Outcome.Win -> Scissors Paper to Outcome.Lose -> Rock Scissors to Outcome.Win -> Rock Scissors to Outcome.Lose -> Paper else -> opponent } } } } fun main() { fun List<String>.splitInput(): List<List<String>> = map { it.split(" ") } fun List<List<String>>.calculateRockPaperScissorsScore( makeMyChoice: (opponent: RockPaperScissors, input: String) -> RockPaperScissors ): Int { val mapped = map { val (opp, me) = it val opponentChoice = RockPaperScissors.parse(opp) val myChoice = makeMyChoice(opponentChoice, me) val fightOutcome = myChoice.fight(opponentChoice) myChoice.value + fightOutcome } return mapped.sumOf { it } } fun part1(input: List<String>): Int = input.splitInput() .calculateRockPaperScissorsScore { _, myChoice -> RockPaperScissors.parse(myChoice) } fun part2(input: List<String>): Int = input.splitInput() .calculateRockPaperScissorsScore { opponentChoice, desiredOutcome -> RockPaperScissors.parse(Outcome.parse(desiredOutcome), opponentChoice) } // 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
0
d0b49770fc313ae42d802489ec757717033a8fda
2,680
advent-of-code-2022
Apache License 2.0
src/main/kotlin/utils/Collections.kt
Arch-vile
433,381,878
false
{"Kotlin": 57129}
package utils /** * Returns all the possible combinations (order does not matter) formed from given values. * Each combination will have at least one element. * * combinations([1,2,3]) => [[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] * * Duplicates are allowed if you feed in duplicates: * combinations([1,2,2]) => [[1], [2], [1, 2], [2, 2], [1, 2, 2]] */ fun <T> combinations(collection: List<T>): Set<List<T>> { val subsets = mutableSetOf<List<T>>() val n: Int = collection.size for (i in 0 until (1 shl n)) { val subset = mutableListOf<T>() for (j in 0 until n) { if (i and (1 shl j) > 0) { subset.add(collection[j]) } } subsets.add(subset) } return subsets.filter { it.isNotEmpty() }.toSet() } fun <T> permutations(set: Set<T>): Set<List<T>> { if (set.isEmpty()) return emptySet() fun <T> allPermutations(list: List<T>): Set<List<T>> { if (list.isEmpty()) return setOf(emptyList()) val result: MutableSet<List<T>> = mutableSetOf() for (i in list.indices) { allPermutations(list - list[i]).forEach { item -> result.add(item + list[i]) } } return result } return allPermutations(set.toList()) } // This seems to flip horizontally and then rotate CW 🤷‍♂️ // btw the nested list means that the first nested list is the first row of the matrix fun <T> transpose(matrix: List<List<T>>): List<List<T>> { return IntRange(0, matrix[0].size - 1) .map { column -> matrix.map { it[column] } } } fun <T> intersect(data: List<List<T>>): List<T> { return data.reduce { acc, list -> acc.intersect(list).toList() } } fun <K, V> merge(maps: List<Map<K, V>>, merger: (V, V) -> V): Map<K, V> { return maps.reduce { acc, next -> merge(acc, next, merger) } } fun <K, V> merge(map1: Map<K, V>, map2: Map<K, V>, merger: (V, V) -> V): Map<K, V> { val mutable = map1.toMutableMap() map2.forEach { if (map1.containsKey(it.key)) { mutable[it.key] = merger(it.value, map1[it.key]!!) } else mutable[it.key] = it.value } return mutable.toMap() } fun <T> Collection<T>.splitAfter(separator: T): List<List<T>> { val result = mutableListOf<MutableList<T>>() var newSublist = true for (item in this) { if (newSublist) result += mutableListOf<T>() result.last() += item newSublist = (item == separator) } return result } class SortedLookup<K, V : Comparable<V>> { private val valueLookup = mutableMapOf<K, V>() private val sortedByValue = sortedSetOf<Pair<K, V>>(Comparator<Pair<K, V>> { o1, o2 -> o1.second.compareTo(o2.second) } .thenComparing { o1, o2 -> o1.first.hashCode().compareTo(o2.first.hashCode()) }) fun add(key: K, value: V) { valueLookup[key] = value sortedByValue.add(Pair(key, value)) } fun drop(key: K): Pair<K, V> { valueLookup.remove(key) val toRemove = sortedByValue.first { it.first == key } sortedByValue.remove(toRemove) return toRemove } fun containsKey(key: K) = valueLookup.contains(key) fun get(key: K) = valueLookup[key] fun sortedSequence() = sortedByValue.asSequence() fun size() = valueLookup.size }
0
Kotlin
0
0
4cdafaa524a863e28067beb668a3f3e06edcef96
3,440
adventOfCode2021
Apache License 2.0
src/main/kotlin/pl/mrugacz95/aoc/day16/day16.kt
mrugacz95
317,354,321
false
null
package pl.mrugacz95.aoc.day16 import pl.mrugacz95.aoc.day2.toInt class Ticket(description: String) { private val groups = description.split("\n\n") private val fields = groups[0].split("\n").map { val field = it.split(": ") val values = field[1].split(" or ") .map { range -> range.split("-") } .map { value -> value[0].toInt()..value[1].toInt() } Pair(field[0], values) }.toList() private val myTicket = groups[1].replace("your ticket:\n", "").split(",").map { it.toInt() } private val nearbyTickets = groups[2].replace("nearby tickets:\n", "") .split("\n") .map { ticket -> ticket.split(",").map { it.toInt() } } override fun toString(): String { return "fields:\n${fields}\nmy ticket:\n${myTicket}\nnearby tickets:\n${nearbyTickets}" } private fun isValueValidForRanges(fieldValue: Int, ranges: List<IntRange>): Boolean { return ranges.any { range -> fieldValue in range } } private fun isValueValidForAllRanges(fieldValue: Int): Boolean { return fields.map { it.second }.any { isValueValidForRanges(fieldValue, it) } } private fun ticketValuesInAllRanges(ticket: List<Int>): Boolean { return ticket.all { isValueValidForAllRanges(it) } } fun sumInvalidFields(): Int { return nearbyTickets.flatten().filter { !isValueValidForAllRanges(it) }.sum() } private fun discardInvalidTickets(): List<List<Int>> { return nearbyTickets.filter { ticketValuesInAllRanges(it) } } private fun guessFieldsNames(validTickets: List<List<Int>>, solver: MarriageSolver<String, Int>): Map<String, Int> { val preferences = fields .withIndex() .associateBy({ it.value.first }, { field -> fields.indices .filter { index -> // matches all ticket values validTickets .map { it[index] } .withIndex() .all { fieldValue -> isValueValidForRanges(fieldValue.value, field.value.second) } } .toSet() }) return solver.solve(preferences) } fun mulDepartureFields(solver: MarriageSolver<String, Int>): Long { val validTickets = discardInvalidTickets() val fieldsMatch = guessFieldsNames(validTickets, solver) return fieldsMatch.entries .filter { it.key.startsWith("departure") } .map { myTicket[it.value].toLong() } .reduce { acc, i -> acc * i } } } abstract class MarriageSolver<K, V> { abstract fun solve(preferences: Map<K, Set<V>>): Map<K, V> } class GreedySolver<K, V> : MarriageSolver<K, V>() { inner class ExclusiveMatrix(private val rows: Set<K>, private val cols: Set<V>) { init { if (rows.size != cols.size) { throw RuntimeException("Cols size must match rows size") } } private val mat = Array(rows.size) { BooleanArray(rows.size) { true } } // all fields match all labels fun match(rowElement: K, colElement: V) { val rowId = rows.indexOf(rowElement) val colId = cols.indexOf(colElement) for (i in mat.indices) { mat[rowId][i] = false mat[i][colId] = false } mat[rowId][colId] = true } fun unmatch(rowElement: K, colElement: V) { val rowId = rows.indexOf(rowElement) val colId = cols.indexOf(colElement) mat[rowId][colId] = false } fun determined(): Boolean { return mat.map { row -> row.filter { it }.count() }.all { it == 1 } } fun getMapping(): Map<K, V> { if (!determined()) { throw RuntimeException("Mapping is not determined yet") } return mat.withIndex() .associateBy( { rows.elementAt(it.index) }, { row -> cols.elementAt(row.value .withIndex() .single { it.value } .index) }) } fun getMatches(rowElement: K): List<V> { return mat[rows.indexOf(rowElement)] .withIndex() .filter { it.value } .map { cols.elementAt(it.index) } } override fun toString(): String { val longestLabel = (rows.map { it.toString().length }.maxByOrNull { it } ?: throw RuntimeException("No max label length found")) + 1 return rows.zip(mat).joinToString("\n", postfix = "\n") { pair -> val matches = getMatches(pair.first) "${pair.first.toString().padEnd(longestLabel)} ${ pair.second.joinToString(" ", transform = { value -> value.toInt().toString() }) } ${pair.second.filter { it }.count()} ${if (matches.size == 1) matches.single().toString() else "?"}" } } } override fun solve(preferences: Map<K, Set<V>>): Map<K, V> { val guesses = ExclusiveMatrix( preferences.keys, preferences.values.flatten().toSet() ) while (!guesses.determined()) { for (preference in preferences) { val matches = guesses.getMatches(preference.key) if (matches.size == 1) { // has match guesses.match(preference.key, matches.first()) continue } for (candidate in preferences.values.flatten()) { preferences[preference.key]?.let { if (candidate !in it) { guesses.unmatch(preference.key, candidate) } } } } } return guesses.getMapping() } } fun main() { val ticket = Ticket({}::class.java.getResource("/day16.in").readText()) println("Answer part 1: ${ticket.sumInvalidFields()}") println("Answer part 2: ${ticket.mulDepartureFields(HopcroftKarpSolver())}") } class HopcroftKarpSolver<U, V> : MarriageSolver<U, V>() { sealed class NodeWrapper<U, V> { class UWrapper<U, V>(val value: U) : NodeWrapper<U, V>() { override fun toString(): String { return value.toString() } } class VWrapper<U, V>(val value: V) : NodeWrapper<U, V>() { override fun toString(): String { return value.toString() } } override fun equals(other: Any?): Boolean { when (other) { is UWrapper<*, *> -> { if (this is UWrapper) return other.value == this.value } is VWrapper<*, *> -> { if (this is VWrapper) return other.value == this.value } } return false } override fun hashCode(): Int { return javaClass.hashCode() } } override fun solve(preferences: Map<U, Set<V>>): Map<U, V> { val uMatching = mutableMapOf<U, V>() val vMatching = mutableMapOf<V, U>() for (u in preferences.keys) { // all nodes if (u !in uMatching.keys) { // not matched u node val queue = ArrayDeque<NodeWrapper<U, V>>() val visited = mutableSetOf<NodeWrapper<U, V>>() val previous = mutableMapOf<NodeWrapper<U, V>, NodeWrapper<U, V>?>() val startNode = NodeWrapper.UWrapper<U, V>(u) queue.add(startNode) // start BFS visited.add(startNode) previous[startNode] = null while (queue.isNotEmpty()) { when (val current = queue.removeFirst()) { is NodeWrapper.UWrapper -> { // u node for (v in preferences[current.value]!!) { // all neighbours val neighbour = NodeWrapper.VWrapper<U, V>(v) if (neighbour !in visited) { // only not visited visited.add(neighbour) // set visited previous[neighbour] = current // set previous queue.add(neighbour) // queue up node } } } is NodeWrapper.VWrapper -> { // v node if (current.value !in vMatching) { // without matching var node = current while (previous[node] != null) { // iterate path to startNode, pseudo DFS if (node is NodeWrapper.VWrapper) { val newMatching = (previous[node]!! as NodeWrapper.UWrapper).value vMatching[node.value] = newMatching uMatching[newMatching] = node.value } node = previous[node]!! } break // found unmatched v node, end loop } else { // has matching val matching = NodeWrapper.UWrapper<U, V>(vMatching[current.value]!!) visited.add(matching) // set visited previous[matching] = current // set previous queue.add(matching) // queue up node } } } } } } return uMatching } }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
10,123
advent-of-code-2020
Do What The F*ck You Want To Public License
src/year_2021/day_04/Day04.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2021.day_04 import readInput import java.lang.NumberFormatException data class BingoSquare( val number: Int, var marked: Boolean = false ) data class Board( val rows: List<List<BingoSquare>> ) { val hasWon: Boolean get() { val rowWin = rows.any { row -> row.all { square -> square.marked } } var columnWin = false for (i in rows.first().indices) { columnWin = columnWin || rows.all { row -> row[i].marked } } return rowWin || columnWin } /** * @return true if creates bingo */ fun mark(number: Int): Boolean { rows.forEach { row -> row .filter { square -> square.number == number } .forEach { square -> square.marked = true } } return hasWon } fun sumUnmarked(): Int { return rows.sumOf { row -> row .filterNot { square -> square.marked } .sumOf { square -> square.number } } } } object Day04 { /** * @return score for the first board to win */ fun solutionOne(text: List<String>): Int { val drawnNumbers = text .first() .split(",") .map { it.toInt() } val boards = parseBoards(text.subList(2, text.size)) drawnNumbers.forEach { number -> boards.forEach { board -> if (board.mark(number)) { return board.sumUnmarked() * number } } } return -1 } /** * @return score of the last board to win */ fun solutionTwo(text: List<String>): Int { val drawnNumbers = text .first() .split(",") .map { it.toInt() } val boards = parseBoards(text.subList(2, text.size)) drawnNumbers.forEach { number -> boards.forEach { board -> if (board.mark(number)) { if (boards.all { board -> board.hasWon }) { return board.sumUnmarked() * number } } } } return -1 } private fun parseBoards(text: List<String>): List<Board> { val boards = mutableListOf<Board>() var rows = mutableListOf<List<BingoSquare>>() text.forEach { line -> if (line.isEmpty()) { boards.add(Board(rows)) rows = mutableListOf() } else { rows.add(line.split(" ").mapNotNull { try { BingoSquare(it.toInt()) } catch (e: NumberFormatException) { null } }) } } boards.add(Board(rows)) return boards } } fun main() { val inputText = readInput("year_2021/day_04/Day04.txt") val solutionOne = Day04.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day04.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
3,150
advent_of_code
Apache License 2.0
src/main/kotlin/day15/Day15.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day15 import java.io.File import java.util.PriorityQueue // Syntax sugar typealias Matrix<T> = Array<Array<T>> typealias RiskFn = (Pair<Int, Int>) -> Int private fun <T> Matrix<T>.get(pair: Pair<Int, Int>) = this[pair.first][pair.second] private fun <T> Matrix<T>.put(pair: Pair<Int, Int>, element: T) { this[pair.first][pair.second] = element } fun parseInput(lines: List<String>): Matrix<Int> = lines .map { it.map(Char::digitToInt).toTypedArray() } .toTypedArray() private fun Pair<Int, Int>.withinBoundaries(limit: Int) = (0 until limit).let { range -> range.contains(this.first) && range.contains(this.second) } // I decided to navigate from destination to start: (N, N) to (0, 0) // Let's try to go up and left first even though there is a priority queue that // will ultimately decide the order private fun Pair<Int, Int>.adjacent(boundaries: Int) = listOf(-1 to 0, 0 to -1, 0 to 1, 1 to 0) // up, left, right, down .map { (first, second) -> (first + this.first) to (second + this.second) } .filter { it.withinBoundaries(boundaries) } private fun solve(dimension: Int, riskFn: RiskFn): Int { val minPathRiskTabulation = Array(dimension) { Array(dimension) { Int.MAX_VALUE } } val toVisit = PriorityQueue<Pair<Pair<Int, Int>, Int>> { (_, risk1), (_, risk2) -> risk1.compareTo(risk2) } val start = 0 to 0 val destination = (dimension - 1) to (dimension - 1) toVisit.add(destination to 0) do { val (current, accumulatedRisk) = toVisit.poll() if (current == start) return accumulatedRisk val pathRisk = riskFn(current) + accumulatedRisk val minPathRisk = minPathRiskTabulation.get(current) if (pathRisk < minPathRisk) { minPathRiskTabulation.put(current, pathRisk) toVisit.addAll(current.adjacent(dimension).associateWith { pathRisk }.toList()) } } while (true) } fun solve1(riskMatrix: Matrix<Int>): Int = solve(riskMatrix.size, riskMatrix::get) fun riskFn2(riskMatrix: Matrix<Int>): RiskFn = { (r, c) -> val additionalRisk = (r / riskMatrix.size) + (c / riskMatrix.size) val risk = riskMatrix[r % riskMatrix.size][c % riskMatrix.size] + additionalRisk if (risk > 9) risk - 9 else risk // only 1..9 (10 resets to 1) } fun solve2(riskMatrix: Matrix<Int>): Int = solve(riskMatrix.size * 5, riskFn2(riskMatrix)) fun main() { File("./input/day15.txt").useLines { lines -> val riskMatrix = parseInput(lines.toList()) println(solve1(riskMatrix)) println(solve2(riskMatrix)) } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
2,492
advent-of-code-2021
MIT License
src/day07/Day07.kt
Ciel-MC
572,868,010
false
{"Kotlin": 55885}
package day07 import readInput sealed interface FileItem { val name: String val size: Int var parent: Folder? fun visit(visitor: (FileItem) -> Unit) } data class Folder(override val name: String, private val children: MutableList<FileItem>, override var parent: Folder?): FileItem { fun addChild(children: FileItem) { children.parent = this this.children.add(children) } fun cd(name: String): Folder { if (name == "..") { return parent as Folder } return children.filterIsInstance<Folder>().first { it.name == name } } override val size: Int get() = children.sumOf { it.size } fun size(predicate: (Folder) -> Boolean): Int { return children.filterIsInstance<Folder>().filter(predicate).sumOf { it.size } } override fun visit(visitor: (FileItem) -> Unit) { visitor(this) children.forEach { it.visit(visitor) } } } data class File(override val name: String, override val size: Int, override var parent: Folder?): FileItem { override fun visit(visitor: (FileItem) -> Unit) { visitor(this) } } fun main() { fun parse(input: List<String>): Folder { val root = Folder("/", mutableListOf(), null) var currentFolder = root input.forEach { line -> if (line.startsWith("$ ")) { val command = line.drop(2) if (command == "cd /") return@forEach when (command.substringBefore(" ")) { "cd" -> { currentFolder = currentFolder.cd(command.substringAfter(" ")) } "ls" -> {} } } else { val type = line.substringBefore(" ") if (type == "dir") { val name = line.substringAfter(" ") currentFolder.addChild(Folder(name, mutableListOf(), currentFolder)) } else { val name = line.substringAfter(" ") val size = type.toInt() currentFolder.addChild(File(name, size, currentFolder)) } } } return root } fun part1(input: List<String>): Int { val root = parse(input) var sum = 0 root.visit { if (it is Folder && it.size < 100000) { sum += it.size } } return sum } fun part2(input: List<String>): Int { val diskSize = 70000000 val requiredSize = 30000000 val root = parse(input) val freeSpace = diskSize - root.size val needed = requiredSize - freeSpace var smallestDir = Int.MAX_VALUE root.visit { item -> if (item is Folder) { val size = item.size if (size >= smallestDir) return@visit // println("Found folder ${item.name} with size $size, which is smaller than $smallestDir") if (size >= needed) { smallestDir = size } } } return smallestDir } val testInput = readInput(7, true) part1(testInput).let { check(it == 95437) { println(it) } } part2(testInput).let { check(it == 24933642) { println(it) } } val input = readInput(7) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7eb57c9bced945dcad4750a7cc4835e56d20cbc8
3,430
Advent-Of-Code
Apache License 2.0
src/Day05.kt
bananer
434,885,332
false
{"Kotlin": 36979}
fun main() { data class Point(val x: Int, val y: Int) data class Line(val start: Point, val end: Point) val lineRegex = Regex("(\\d+),(\\d+) -> (\\d+),(\\d+)") infix fun Int.towards(b: Int): IntProgression { return if (this < b) { this .. b } else { (b .. this).reversed() } } fun parseInput(input: List<String>): List<Line> { return input.map { val matches = lineRegex.matchEntire(it) ?: throw IllegalArgumentException("Could not parse: '$it'") val (x1, y1, x2, y2) = matches.groupValues.drop(1).map { g -> g.toInt() } Line(Point(x1, y1), Point(x2, y2)) } } fun part1(input: List<String>): Int { val lines = parseInput(input) // For now, only consider horizontal and vertical lines .filter { it.start.x == it.end.x || it.start.y == it.end.y } val map = mutableMapOf<Point, Int>() for (line in lines) { for (x in (line.start.x towards line.end.x)) { for (y in (line.start.y towards line.end.y)) { // map[x,y]++ map.compute(Point(x, y)) { _, v -> (v ?: 0) + 1 } } } } return map.values.count { it >= 2 } } fun part2(input: List<String>): Int { val lines = parseInput(input) val map = mutableMapOf<Point, Int>() for (line in lines) { val xs = (line.start.x towards line.end.x).toList() val ys = (line.start.y towards line.end.y).toList() val points = if (xs.size == 1) { ys.map { Point(xs[0], it) } } else if(ys.size == 1) { xs.map { Point(it, ys[0]) } } else if(xs.size == ys.size) { xs.mapIndexed { index, x -> Point(x, ys[index]) } } else { throw IllegalStateException("Not horizontal, vertical or 45 degree diagonal") } for (p in points) { map.compute(p) { _, v -> (v ?: 0) +1 } } } return map.values.count { it >= 2 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") val testOutput1 = part1(testInput) println("test output1: $testOutput1") check(testOutput1 == 5) val testOutput2 = part2(testInput) println("test output2: $testOutput2") check(testOutput2 == 12) val input = readInput("Day05") println("output part1: ${part1(input)}") println("output part2: ${part2(input)}") }
0
Kotlin
0
0
98f7d6b3dd9eefebef5fa3179ca331fef5ed975b
2,654
advent-of-code-2021
Apache License 2.0
src/main/kotlin/aoc2015/AllInASingleNight.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2015 import komu.adventofcode.utils.nonEmptyLines fun allInASingleNight(input: String, longest: Boolean = false): Int { val legs = Leg.parseAll(input) val cities = legs.flatMap { it.cities }.toSet() val best = if (longest) Collection<Int>::maxOrNull else Collection<Int>::minOrNull fun recurse(currentCity: String, distance: Int, visited: List<String>): Int? { if (visited.size == cities.size) return distance val candidateLegs = legs.filter { it.from == currentCity && it.to !in visited } return best(candidateLegs.mapNotNull { leg -> recurse(leg.to, distance + leg.distance, visited + leg.to) }) } return best(cities.mapNotNull { city -> recurse(city, 0, listOf(city)) }) ?: error("no route") } private data class Leg(val from: String, val to: String, val distance: Int) { val cities: List<String> get() = listOf(from, to) fun reverse() = Leg(to, from, distance) companion object { private val regex = Regex("""(.+) to (.+) = (\d+)""") fun parseAll(s: String): List<Leg> { val legs = s.nonEmptyLines().map { parse(it) } return legs + legs.map { it.reverse() } } fun parse(s: String): Leg { val m = regex.matchEntire(s) ?: error("invalid input '$s'") return Leg(m.groupValues[1], m.groupValues[2], m.groupValues[3].toInt()) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,478
advent-of-code
MIT License
src/Day12.kt
matusekma
572,617,724
false
{"Kotlin": 119912, "JavaScript": 2024}
open class Vertex( val name: Char, val height: Char, val edges: MutableList<Vertex> = mutableListOf() ) private fun buildGraph(input: List<String>): MutableList<MutableList<Vertex>> { val grid = mutableListOf<MutableList<Vertex>>() for (line in input) { grid.add(line.toCharArray().map { Vertex(it, if (it == 'S') 'a' else if (it == 'E') 'z' else it) } .toMutableList()) } for (row in grid) { for (i in 0 until row.size - 1) { if (row[i].height + 1 >= row[i + 1].height) { row[i].edges.add(row[i + 1]) } if (row[i].height <= row[i + 1].height + 1) { row[i + 1].edges.add(row[i]) } } } for (i in 0 until grid[0].size) { for (j in 0 until grid.size - 1) { if (grid[j][i].height + 1 >= grid[j + 1][i].height) { grid[j][i].edges.add(grid[j + 1][i]) } if (grid[j][i].height <= grid[j + 1][i].height + 1) { grid[j + 1][i].edges.add(grid[j][i]) } } } return grid } class Day12 { fun part1(input: List<String>): Double { val grid = buildGraph(input) var start: Vertex? = null var end: Vertex? = null grid.forEach { it.forEach { v -> if (v.name == 'S') start = v else if (v.name == 'E') end = v } } val vertexList = grid.flatten() return dijkstra(start!!, end!!, vertexList) } private fun dijkstra(startNode: Vertex, endNode: Vertex, vertexList: List<Vertex>): Double { val distances = mutableMapOf<Vertex, Double>() distances[startNode] = 0.0 val q = mutableSetOf<Vertex>() for (vertex in vertexList) { if (vertex != startNode) distances[vertex] = Double.MAX_VALUE q.add(vertex) } while (q.isNotEmpty()) { val v = q.minBy { distances[it]!! } q.remove(v) for (neighbor in v.edges) { if (q.contains(neighbor)) { val alt = distances[v]!! + 1.0 if (alt < distances[neighbor]!!) { distances[neighbor] = alt } } } if(v == endNode){ distances[endNode]!! } } return distances[endNode]!! } fun part2(input: List<String>): Double { val grid = buildGraph(input) val starts = mutableListOf<Vertex>() var end: Vertex? = null grid.forEach { it.forEach { v -> if (v.height == 'a') starts.add(v) else if (v.name == 'E') end = v } } val vertexList = grid.flatten() return starts.map { dijkstra(it, end!!, vertexList) }.min() } } fun main() { val input = readInput("input12_1") println(Day12().part1(input)) println(Day12().part2(input)) }
0
Kotlin
0
0
744392a4d262112fe2d7819ffb6d5bde70b6d16a
2,902
advent-of-code
Apache License 2.0
src/Day15.kt
frungl
573,598,286
false
{"Kotlin": 86423}
import kotlin.math.abs import kotlin.math.max import kotlin.math.min typealias Coordinate = Pair<Int, Int> fun main() { fun parse(input: List<String>): List<Pair<Coordinate, Coordinate>> = input.asSequence() .map { it.split(": ").toList() } .map { it[0].substringAfter("at ") to it[1].substringAfter("at ") } .map { it.first.split(", ").toList() to it.second.split(", ").toList()} .map { Pair( it.first[0].substringAfter('=').toInt() to it.first[1].substringAfter('=').toInt(), it.second[0].substringAfter('=').toInt() to it.second[1].substringAfter('=').toInt() ) }.toList() fun distance(a: Coordinate, b: Coordinate): Int = abs(a.first - b.first) + abs(a.second - b.second) fun part1(input: List<String>, layer: Int): Int { val data = parse(input) val used = mutableSetOf<Int>() val beacons = mutableSetOf<Int>() data.forEach { val (s, b) = it val dst = distance(s, b) val size = dst - abs(layer - s.second) if (size >= 0) { used.addAll(s.first - size .. s.first + size) if (b.second == layer) beacons.add(b.first) } } return used.size - beacons.size } fun part2(input: List<String>, limit: Int): Long { var x = -1 var y = -1 val data = parse(input) (0..limit).forEach { layer -> val used = mutableListOf<Pair<Int, Int>>() data.forEach { val (s, b) = it val dst = distance(s, b) val size = dst - abs(layer - s.second) if (size >= 0) { used.add(max(0, s.first - size) to min(limit, s.first + size)) } } used.add(-1 to -1) used.add(limit + 1 to limit + 1) used.sortBy { it.first } var mx = -1 used.windowed(2) { val (f, s) = it mx = max(mx, f.second) if (mx + 1 < s.first) { x = mx + 1 y = layer } } } return x.toLong() * 4_000_000L + y.toLong() } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") println(part1(input, 2_000_000)) println(part2(input, 4_000_000)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
2,584
aoc2022
Apache License 2.0
src/Day03.kt
treegem
572,875,670
false
{"Kotlin": 38876}
import common.readInput fun main() { val day = "03" fun part1(input: List<String>) = input .map { findBadlyPackedItem(it) } .sumOf { getPriority(it) } fun part2(input: List<String>): Int { return input .chunked(3) .map { findBatch(it) } .sumOf { getPriority(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) } private fun findBadlyPackedItem(line: String): Char { val compartmentSize = line.length / 2 val firstCompartmentItems = line.take(compartmentSize).toSet() val secondCompartmentItems = line.takeLast(compartmentSize).toSet() val correctlyPackedItemsInFirstCompartment = firstCompartmentItems - secondCompartmentItems return (firstCompartmentItems - correctlyPackedItemsInFirstCompartment).single() } private fun getPriority(item: Char) = if (item.isLowerCase()) { item.code - 'a'.code + 1 } else { item.code - 'A'.code + 27 } private fun findBatch(lines: List<String>): Char { require(lines.size == 3) val (firstBag, secondBag, thirdBag) = lines.map { it.toSet() } return firstBag.toSet() .filter { it in secondBag } .filter { it in thirdBag } .toCharArray() .single() }
0
Kotlin
0
0
97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8
1,491
advent_of_code_2022
Apache License 2.0
advent2022/src/main/kotlin/year2022/Day15.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay import kotlin.math.absoluteValue private fun manhattenDistance(x: Long, y: Long, foundX: Long, foundY: Long) = (x - foundX).absoluteValue + (y - foundY).absoluteValue class Day15(private val row: Long, private val maxCoordinate: Int) : AdventDay(2022, 15) { data class Sensor(val x: Long, val y: Long, val foundX: Long, val foundY: Long) { fun safeRangForRow(row: Long): LongRange? { val dst = manhattenDistance(x, y, foundX, foundY) val dstToY = (y - row).absoluteValue val width = dst - dstToY if (width > 0) { // Add a start/end of safe spot indexes return (x - width..x + width) } return null } companion object { fun of(input: String): Sensor { val (a, b) = input.split(":") val (x1, y1) = a.split(",") val (x) = x1.split("=").mapNotNull { it.toLongOrNull() } val (y) = y1.split("=").mapNotNull { it.toLongOrNull() } val (x2, y2) = b.split(",") val (foundX) = x2.split("=").mapNotNull { it.toLongOrNull() } val (foundY) = y2.split("=").mapNotNull { it.toLongOrNull() } return Sensor(x, y, foundX, foundY) } } } data class Area(val sensors: List<Sensor>) { private val maxXOfSet = sensors.maxOf { sensors.maxOf { s -> (s.x - s.foundX).absoluteValue } } private val minX = sensors.minOf { listOf(it.x - maxXOfSet, it.foundX, 0).min() } private val maxX = sensors.maxOf { listOf(it.x + maxXOfSet, it.foundX, 0).max() } fun countNonDistressSignalInRow(row: Long, mX: Long = minX, maX: Long = maxX): Int = (mX..maX).filter { x -> sensors.any { s -> manhattenDistance(s.x, s.y, s.foundX, s.foundY) >= manhattenDistance(x, row, s.x, s.y) && !(s.foundX == x && s.foundY == row) } }.size fun safeRangForRow(row: Long): List<LongRange> = sensors.mapNotNull { s -> s.safeRangForRow(row) } companion object { fun of(input: List<String>): Area = Area(input.map { Sensor.of(it) }) } } override fun part1(input: List<String>): Int { val area = Area.of(input) return area.countNonDistressSignalInRow(row) } override fun part2(input: List<String>): Long { val area = Area.of(input) val safeRangesPerLine = Array<List<LongRange>>(maxCoordinate + 1) { mutableListOf() } for (row in 0..maxCoordinate) { safeRangesPerLine[row] = area.safeRangForRow(row.toLong()) } safeRangesPerLine.forEachIndexed { y, ranges -> val sortedRanges = ranges.sortedBy { it.first } var highest = sortedRanges.first().last // Find first set of ranges with a gap sortedRanges.drop(1).forEach { if (it.first > highest) { return (it.first - 1) * 4000000 + y } if (it.last > highest) { highest = it.last } } } return -1 } } fun main() = Day15(2_000_000, 4_000_000).run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
3,366
advent-of-code
Apache License 2.0
src/Day01.kt
KristianAN
571,726,775
false
{"Kotlin": 9011}
fun main() { fun part1(input: List<String>): Int = input.foldIndexed(MaxCalories(0,0)) { index, acc, s -> if (s.isEmpty()) { val calories = input.subList(acc.startIndex, index).fold(0) { accum, n -> n.toInt() + accum } if (calories > acc.currentMax) MaxCalories(calories, index + 1) else MaxCalories(acc.currentMax, index + 1) } else { acc } }.currentMax fun part2(input: List<String>): Int = input.foldIndexed(MaxCalories2.emptyMC()) { index, acc: MaxCalories2, s -> if (s.isEmpty()) { val calories = input.subList(acc.startIndex, index).fold(0) { accum, n -> n.toInt() + accum } MaxCalories2(acc.currentMax.update(calories), index + 1) } else { acc } }.currentMax.sum() // test if implementation meets criteria from the description, like: val input = readInput("day01") println(part1(input)) println(part2(input)) } data class MaxCalories( val currentMax: Int, val startIndex: Int, ) data class MaxCalories2( val currentMax: MaxValues, val startIndex: Int, ) { companion object { fun emptyMC() = MaxCalories2(MaxValues.emptyMV(), 0) } } data class MaxValues( val first: Int, val second: Int, val third: Int, ) { fun update(num: Int): MaxValues = if (num > first) MaxValues(num, first, second) else if (num > second) MaxValues(first, num, second) else if (num > third) MaxValues(first, second, num) else this fun sum() = first + second + third companion object { fun emptyMV() = MaxValues(0, 0, 0) } }
0
Kotlin
0
0
3a3af6e99794259217bd31b3c4fd0538eb797941
1,750
AoC2022Kt
Apache License 2.0
src/Day24Part1.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
import Day24Part1.part1 import kotlin.math.max import kotlin.math.min object Day24Part1 { data class XYZ( val x: Double, val y: Double, val z: Double, ) data class Path( val p1: XYZ, val p2: XYZ, ) { fun onPath(x: Double, y: Double): Boolean { val xRange = listOf(p1.x, p2.x).sorted() val yRange = listOf(p1.y, p2.y).sorted() return xRange[0] <= x && x <= xRange[1] && yRange[0] <= y && y <= yRange[1] } } data class Hailstone( val pos: XYZ, val vel: XYZ, ) { // y = mx + b private val m = vel.y / vel.x private val b = pos.y - (m * pos.x) companion object { fun init(line: String): Hailstone { val (pos, vel) = line.split("@", limit = 2) return Hailstone( pos = pos.split(",", limit = 3).map { it.trim().toDouble() }.let { (x, y, z) -> XYZ(x, y, z) }, vel = vel.split(",", limit = 3).map { it.trim().toDouble() }.let { (x, y, z) -> XYZ(x, y, z) }, ) } } private fun pathAtBoundary(mn: Double, mx: Double): Path { val (x0, x1) = timeAtBoundary(pos.x, vel.x, mn, mx) val (y0, y1) = timeAtBoundary(pos.y, vel.y, mn, mx) val t0 = max(x0, y0) val t1 = min(x1, y1) return Path( p1 = XYZ(pos.x + vel.x * t0, pos.y + vel.y * t0, 0.0), p2 = XYZ(pos.x + vel.x * t1, pos.y + vel.y * t1, 0.0), ) } fun crosses(h2: Hailstone, mn: Double, mx: Double): Boolean { val h1 = this // Parallel if (h1.m == h2.m) return false // Find crossing point val x = (h1.b - h2.b) / (h2.m - h1.m) val y = h1.m * x + h1.b // If crossing point is out of range, return false if (x < mn || x > mx || y < mn || y > mx) return false // If crossing point is on path for both hailstones return h1.pathAtBoundary(mn, mx).onPath(x, y) && h2.pathAtBoundary(mn, mx).onPath(x, y) } } fun timeAtBoundary(p: Double, v: Double, mn: Double, mx: Double): List<Double> { val t0 = (mn - p) / v val t1 = (mx - p) / v return listOf(max(0.0, t0), max(0.0, t1)).sorted() } fun part1(input: List<String>): Int { val pvs = input.map { Hailstone.init(it) } var count = 0 val mn = 200000000000000.0 val mx = 400000000000000.0 (0..<pvs.size - 1).forEach { i -> val h1 = pvs[i] (i + 1..<pvs.size).forEach { j -> val h2 = pvs[j] if (h1.crosses(h2, mn, mx)) count += 1 } } return count } } fun main() { val input = readInput("Day24") part1(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
2,965
aoc-2023
Apache License 2.0