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/day18/Day18.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day18
import readInput
enum class Axis { X, Y, Z }
data class Side(val x: Int, val y: Int, val z: Int, val axis: Axis) {
companion object {
fun fromCoordinatesAndAxis(coordinates: Triple<Int, Int, Int>, axis: Axis): Side =
Side(coordinates.first, coordinates.second, coordinates.third, axis)
}
}
fun Triple<Int, Int, Int>.incrementAxis(axis: Axis): Triple<Int, Int, Int> = when (axis) {
Axis.X -> Triple(first + 1, second, third)
Axis.Y -> Triple(first, second + 1, third)
Axis.Z -> Triple(first, second, third + 1)
}
class Cube {
private val sides = mutableSetOf<Side>()
private var duplicates = mutableSetOf<Side>()
fun build(input: Collection<Triple<Int, Int, Int>>) = input.forEach {
Axis.values().forEach { axis ->
if (!sides.add(Side.fromCoordinatesAndAxis(it, axis))) duplicates.add(Side.fromCoordinatesAndAxis(it, axis))
if (!sides.add(Side.fromCoordinatesAndAxis(it.incrementAxis(axis), axis)))
duplicates.add(Side.fromCoordinatesAndAxis(it.incrementAxis(axis), axis))
}
}
fun getAllSidesCount() = sides.size - duplicates.size
fun intersect(other: Cube): Cube = Cube().also {
it.sides.addAll(sides.intersect(other.sides))
it.duplicates.addAll(duplicates.intersect(other.duplicates))
}
}
fun Triple<Int, Int, Int>.isInBoundary(
boundaryX: Pair<Int, Int>,
boundaryY: Pair<Int, Int>,
boundaryZ: Pair<Int, Int>
) = first >= boundaryX.first && first <= boundaryX.second
&& second >= boundaryY.first && second <= boundaryY.second
&& third >= boundaryZ.first && third <= boundaryZ.second
fun Triple<Int, Int, Int>.neighbors() = listOf(
Triple(first + 1, second, third),
Triple(first - 1, second, third),
Triple(first, second + 1, third),
Triple(first, second - 1, third),
Triple(first, second, third + 1),
Triple(first, second, third - 1),
)
fun main() {
fun part1(input: List<Triple<Int, Int, Int>>): Int {
return Cube().also { it.build(input) }.getAllSidesCount()
}
fun part2(input: List<Triple<Int, Int, Int>>): Int {
val cube = Cube().also { it.build(input) }
val boundaryX = Pair(input.minOf { it.first } - 1, input.maxOf { it.first } + 1)
val boundaryY = Pair(input.minOf { it.second } - 1, input.maxOf { it.second } + 1)
val boundaryZ = Pair(input.minOf { it.third } - 1, input.maxOf { it.third } + 1)
val visited = mutableListOf<Triple<Int, Int, Int>>()
val queue = mutableListOf(Triple(boundaryX.first, boundaryY.first, boundaryZ.first))
while (queue.isNotEmpty()) {
val next = queue.removeFirst()
for (e in next.neighbors()) {
if (e.isInBoundary(boundaryX, boundaryY, boundaryZ) && !visited.contains(e) && !input.contains(e)) {
queue.add(e)
visited.add(e)
}
}
}
val cubeOutside = Cube().also { it.build(visited) }
val intersected = cube.intersect(cubeOutside)
return intersected.getAllSidesCount()
}
fun preprocess(input: List<String>): List<Triple<Int, Int, Int>> = input.map { row ->
val split = row.split(",").map { it.toInt() }
Triple(split[0], split[1], split[2])
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(18, true)
check(part1(preprocess(testInput)) == 64)
val input = readInput(18)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) == 58)
println(part2(preprocess(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 3,664 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D21.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2020
import io.github.pshegger.aoc.common.BaseSolver
class Y2020D21 : BaseSolver() {
override val year = 2020
override val day = 21
override fun part1(): Int {
val foods = parseInput()
val possibilities = foods.calculatePossibleAllergens()
val nonAllergenic = foods.fold(emptySet<String>()) { acc, food -> acc + food.ingredients } -
possibilities.values.fold(emptySet()) { acc, set -> acc + set }
return foods.sumOf { food -> food.ingredients.count { it in nonAllergenic } }
}
override fun part2(): String {
val possibilities = parseInput().calculatePossibleAllergens().toMutableMap()
val solved = mutableMapOf<String, String>()
while (possibilities.isNotEmpty()) {
val (key, valueSet) = possibilities.entries.first { it.value.size == 1 }
val value = valueSet.single()
possibilities.remove(key)
for ((otherKey, otherValue) in possibilities) {
possibilities[otherKey] = otherValue - value
}
solved[key] = value
}
return solved.toList().sortedBy { it.first }.joinToString(",") { it.second }
}
private fun List<Food>.calculatePossibleAllergens(): Map<String, Set<String>> =
fold(mapOf()) { acc0, food ->
food.allergens.fold(acc0) { acc, allergen ->
if (allergen in acc) {
(acc - allergen) + mapOf(
Pair(
allergen,
(acc[allergen] ?: error("WTF")).intersect(food.ingredients)
)
)
} else {
(acc - allergen) + mapOf(allergen to food.ingredients)
}
}
}
private fun parseInput() = readInput {
readLines().map { line ->
val ingredients = line.takeWhile { it != '(' }
.split(" ")
.filter { it.isNotBlank() }
.toSet()
val allergens = line.dropWhile { it != '(' }
.drop(1)
.dropLast(1)
.split(",")
.mapIndexed { index, s -> if (index == 0) s.split(" ")[1].trim() else s.trim() }
.toSet()
Food(ingredients, allergens)
}
}
private data class Food(val ingredients: Set<String>, val allergens: Set<String>)
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 2,482 | advent-of-code | MIT License |
src/year2023/19/Day19.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`19`
import readInput
import utils.printlnDebug
private const val CURRENT_DAY = "19"
data class XmasRanged(
val x: IntRange,
val m: IntRange,
val a: IntRange,
val s: IntRange,
) {
fun countAll(): Long {
return x.count().toLong() * m.count() * a.count() * s.count()
}
}
data class Xmas(
val x: Int,
val m: Int,
val a: Int,
val s: Int,
) {
fun sum(): Int = x + m + a + s
}
sealed class Rule {
data class Less(
val key: String,
val num: Int,
val destination: String,
) : Rule()
data class More(
val key: String,
val num: Int,
val destination: String,
) : Rule()
data class Terminal(
val destination: String
) : Rule()
}
data class Workflow(
val key: String,
val rules: List<Rule>,
)
fun String.toRule(): Rule {
return when {
contains("<") -> {
val split = split("<", ":")
Rule.Less(
key = split.first(),
num = split[1].toInt(),
destination = split[2],
)
}
contains(">") -> {
val split = split(">", ":")
Rule.More(
key = split.first(),
num = split[1].toInt(),
destination = split[2],
)
}
else -> Rule.Terminal(
destination = this,
)
}
}
fun String.toRules(): List<Rule> {
return split(",")
.map { it.trim() }
.filter { it.isNotBlank() }
.map { it.toRule() }
}
fun lineToWorkflow(line: String): Workflow {
val key = line.split("{").first()
val rulesLine = line.substring(
line.indexOfFirst { it == '{' }.inc(),
line.indexOfLast { it == '}' },
)
return Workflow(
key = key,
rules = rulesLine.toRules()
)
}
fun String.toKeyValue(): Pair<String, Int> {
val split = split("=")
return split.first() to split.last().toInt()
}
fun lineToXmas(line: String): Xmas {
val xmasLine = line.substring(
line.indexOfFirst { it == '{' },
line.indexOfLast { it == '}' },
)
val pairs = xmasLine.split(",")
.map { it.trim() }
.map { it.toKeyValue() }
return Xmas(
pairs[0].second,
pairs[1].second,
pairs[2].second,
pairs[3].second,
)
}
private fun List<Workflow>.asMapOfWorkflows(): Map<String, List<Rule>> {
return associate { it.key to it.rules }
}
private fun processAll(
xmases: List<Xmas>,
workflows: List<Workflow>,
initialKey: String,
): Int {
val workflowsMap: Map<String, List<Rule>> = workflows.asMapOfWorkflows()
val res = xmases.map {
var currentKey = initialKey
while (currentKey !in listOf("R", "A")) {
currentKey = processXmas(it, workflowsMap[currentKey]!!)
}
it to currentKey
}
printlnDebug { res }
return res
.filter { it.second == "A" }
.sumOf { (xmas, _) -> xmas.sum() }
}
private fun processAllRanged(
xmases: XmasRanged,
workflows: List<Workflow>,
initialKey: String
): Long {
val workflowsMap: Map<String, List<Rule>> = workflows.asMapOfWorkflows()
var currentKey: Map<XmasRanged, String> = mapOf(xmases to initialKey)
while (currentKey.values.any { it !in listOf("R", "A") }) {
val mutableMap: MutableMap<XmasRanged, String> = mutableMapOf()
currentKey.forEach { (xmasRanged, key) ->
if (key in listOf("R", "A")) {
mutableMap[xmasRanged] = key
} else {
val foundRules = workflowsMap[key] ?: error("CouldNotFindWorkflows for key $key")
val map = processXmasRanged(xmasRanged, foundRules)
mutableMap.putAll(map)
}
}
currentKey = mutableMap
}
val resMap = currentKey.filter { it.value == "A" }
return resMap.keys.sumOf { it.countAll() }
}
private fun processXmas(
xmas: Xmas,
rules: List<Rule>,
): String {
val xmasMap = mapOf(
"x" to xmas.x,
"m" to xmas.m,
"a" to xmas.a,
"s" to xmas.s,
)
rules.forEach {
when (it) {
is Rule.Less -> {
val value = xmasMap[it.key] ?: error("Nothing found for ${it.key}")
if (value < it.num) return it.destination
}
is Rule.More -> {
val value = xmasMap[it.key]!!
if (value > it.num) return it.destination
}
is Rule.Terminal -> {
return it.destination
}
}
}
error("IMPOSSIBLE STATE XMAS:$xmas Rules:$rules")
}
// The batch satisfying 1≤x<1637, 1341≤m<2683, 3078≤a<3149, 1477≤s<4001 has a total size of 393444532448.
private fun processXmasRanged(
xmas: XmasRanged,
rules: List<Rule>,
): Map<XmasRanged, String> {
val resultMap = mutableMapOf<XmasRanged, String>()
var uXmas = xmas
rules.forEach { rule ->
val xmasRangeMap = mapOf(
"x" to uXmas.x,
"m" to uXmas.m,
"a" to uXmas.a,
"s" to uXmas.s,
)
when (rule) {
is Rule.Less -> {
val range = xmasRangeMap[rule.key] ?: error("Nothing found for ${rule.key}")
if (rule.num in range) {
val acceptedXmas = when (rule.key) {
"x" -> uXmas.copy(x = range.first until rule.num)
"m" -> uXmas.copy(m = range.first until rule.num)
"a" -> uXmas.copy(a = range.first until rule.num)
"s" -> uXmas.copy(s = range.first until rule.num)
else -> error("Illegal key:${rule.key}")
}
val goNextXmas = when (rule.key) {
"x" -> uXmas.copy(x = rule.num..range.last)
"m" -> uXmas.copy(m = rule.num..range.last)
"a" -> uXmas.copy(a = rule.num..range.last)
"s" -> uXmas.copy(s = rule.num..range.last)
else -> error("Illegal key:${rule.key}")
}
resultMap[acceptedXmas] = rule.destination
uXmas = goNextXmas
} else {
error("I DONT KNOW RETURN HERE??")
}
}
is Rule.More -> {
val range = xmasRangeMap[rule.key] ?: error("Nothing found for ${rule.key}")
if (rule.num in range) {
val goNextXmas = when (rule.key) {
"x" -> uXmas.copy(x = range.first..rule.num)
"m" -> uXmas.copy(m = range.first..rule.num)
"a" -> uXmas.copy(a = range.first..rule.num)
"s" -> uXmas.copy(s = range.first..rule.num)
else -> error("Illegal key:${rule.key}")
}
val acceptedXmas = when (rule.key) {
"x" -> uXmas.copy(x = rule.num + 1..range.last)
"m" -> uXmas.copy(m = rule.num + 1..range.last)
"a" -> uXmas.copy(a = rule.num + 1..range.last)
"s" -> uXmas.copy(s = rule.num + 1..range.last)
else -> error("Illegal key:${rule.key}")
}
resultMap[acceptedXmas] = rule.destination
uXmas = goNextXmas
} else {
error("I DONT KNOW RETURN HERE??")
}
}
is Rule.Terminal -> {
resultMap[uXmas] = rule.destination
}
}
}
return resultMap
}
fun main() {
fun part1(input: List<String>): Int {
val tookLines = input.takeWhile { it.isNotBlank() }
val workflows = tookLines.map {
lineToWorkflow(it)
}
val xmasLines = input.reversed()
.takeWhile { it.isNotBlank() }
.reversed()
val xmases = xmasLines.map {
lineToXmas(it)
}
printlnDebug { workflows }
printlnDebug { xmases }
return processAll(xmases, workflows, "in")
}
fun part2(input: List<String>): Long {
val tookLines = input.takeWhile { it.isNotBlank() }
val workflows = tookLines.map {
lineToWorkflow(it)
}
val initialRange = XmasRanged(
x = 1..4000,
m = 1..4000,
a = 1..4000,
s = 1..4000,
)
printlnDebug { workflows }
return processAllRanged(
initialRange,
workflows,
"in"
)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 19114)
val part2Test = part2(testInput)
println(part2Test)
check(part2Test == 167409079868000L)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input)
println(part1)
check(part1 == 319062)
// Part 2
val part2 = part2(input)
println(part2)
check(part2 == 118638369682135L)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 9,385 | KotlinAdventOfCode | Apache License 2.0 |
src/Day18.kt | zirman | 572,627,598 | false | {"Kotlin": 89030} | sealed interface LavaCube {
object Lava : LavaCube
object Air : LavaCube
object Visited : LavaCube
}
typealias LavaMatrix = List<List<MutableList<LavaCube>>>
fun main() {
fun LavaMatrix.widths(): Triple<Int, Int, Int> {
return Triple(this[0][0].size, this[0].size, size)
}
fun parseLavaGridInfo(input: List<String>): LavaMatrix {
val drops = input.map { line ->
val (x, y, z) = line.split(",")
Triple(x.toInt(), y.toInt(), z.toInt())
}
val minX = drops.minOf { (x, _, _) -> x }
val maxX = drops.maxOf { (x, _, _) -> x }
val minY = drops.minOf { (_, y, _) -> y }
val maxY = drops.maxOf { (_, y, _) -> y }
val minZ = drops.minOf { (_, _, z) -> z }
val maxZ = drops.maxOf { (_, _, z) -> z }
val widthX = maxX - minX + 3
val widthY = maxY - minY + 3
val widthZ = maxZ - minZ + 3
val grid = List(widthZ) { List(widthY) { MutableList<LavaCube>(widthX) { LavaCube.Air } } }
drops.forEach { (x, y, z) ->
grid[z - minZ + 1][y - minY + 1][x - minX + 1] = LavaCube.Lava
}
return grid
}
fun floodFillSearch(grid: LavaMatrix): DeepRecursiveFunction<Triple<Int, Int, Int>, Int> {
val (widthX, widthY, widthZ) = grid.widths()
return DeepRecursiveFunction { (x: Int, y: Int, z: Int) ->
if (x !in 0 until widthX ||
y !in 0 until widthY ||
z !in 0 until widthZ
) return@DeepRecursiveFunction 0
when (grid[z][y][x]) {
LavaCube.Visited -> 0
LavaCube.Lava -> 1
LavaCube.Air -> {
grid[z][y][x] = LavaCube.Visited
callRecursive(Triple(x - 1, y, z)) +
callRecursive(Triple(x + 1, y, z)) +
callRecursive(Triple(x, y - 1, z)) +
callRecursive(Triple(x, y + 1, z)) +
callRecursive(Triple(x, y, z - 1)) +
callRecursive(Triple(x, y, z + 1))
}
}
}
}
fun part1(input: List<String>): Int {
val grid = parseLavaGridInfo(input)
val (widthX, widthY, widthZ) = grid.widths()
val search = floodFillSearch(grid)
return (0 until widthZ).sumOf { z ->
(0 until widthY).sumOf { y ->
(0 until widthX).sumOf { x ->
if (grid[z][y][x] == LavaCube.Air) {
search(Triple(x, y, z))
} else {
0
}
}
}
}
}
fun part2(input: List<String>): Int {
val grid = parseLavaGridInfo(input)
return floodFillSearch(grid)(Triple(0, 0, 0))
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
check(part1(testInput) == 64)
val input = readInput("Day18")
println(part1(input))
check(part2(testInput) == 58)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 2ec1c664f6d6c6e3da2641ff5769faa368fafa0f | 3,149 | aoc2022 | Apache License 2.0 |
2021/src/day12/Day12.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day12
import readInput
fun buildGraph(lines: List<String>) : Map<String, MutableSet<String>> {
val points = mutableMapOf<String, MutableSet<String>>()
for (line in lines) {
val connexion = line.split("-")
val from = connexion[0]
val to = connexion[1]
if (points.contains(from)) {
points[from]?.add(to)
} else {
points.put(from, mutableSetOf(to))
}
if (points.contains(to)) {
points[to]?.add(from)
} else {
points.put(to, mutableSetOf(from))
}
}
return points
}
fun String.isAllLowerCase() = !this.any { it.isUpperCase() }
fun visitGraph(
start: String,
graph: Map<String, MutableSet<String>>,
visited: Map<String, Int>, // mapOf("cave" -> numberOfVisits)
canVisitOneSmallCaveTwice: Boolean,
cache: MutableMap<String, Int> = mutableMapOf() // mapOf("node+visited" => numberOfPathsTillEnd)
) : Int {
val toVisit = mutableListOf<String>()
var nbPath = 0
for (node in graph[start]!!) {
when (node) {
"end" -> nbPath++
"start" -> { } // Do no re-visit start
else -> {
if (visited.getOrDefault(node, 0) < 1) {
toVisit.add(node)
} else if (canVisitOneSmallCaveTwice && !visited.values.contains(2)) {
toVisit.add(node)
}
}
}
}
while (!toVisit.isEmpty()) {
val item = toVisit.removeAt(toVisit.lastIndex)
val nextVisited = visited.toMutableMap()
if (item.isAllLowerCase()) { // small cave
nextVisited[item] = visited.getOrDefault(item, 0) + 1 // add one visit to that cave
}
val cacheKey = item + nextVisited.toString()
if (!cache.contains(cacheKey)) {
cache[cacheKey] = visitGraph(item, graph, nextVisited, canVisitOneSmallCaveTwice, cache)
}
nbPath += cache[cacheKey]!!
}
return nbPath
}
fun part1(lines: List<String>) : Int {
val graph = buildGraph(lines)
println(graph)
return visitGraph("start", graph, mapOf(), false)
}
fun part2(lines: List<String>) : Int {
val graph = buildGraph(lines)
return visitGraph("start", graph, mapOf(), true)
}
fun main() {
val simpleInput = readInput("day12/simple")
println("part1(simpleInput) => " + part1(simpleInput))
println("part2(simpleInput) => " + part2(simpleInput))
val larger = readInput("day12/larger")
println("part1(larger) => " + part1(larger))
println("part2(larger) => " + part2(larger))
val evenLarger = readInput("day12/even_larger")
println("part1(evenLarger) => " + part1(evenLarger))
println("part2(evenLarger) => " + part2(evenLarger))
val input = readInput("day12/input")
println("part1(input) => " + part1(input))
println("part1(input) => " + part2(input))
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 2,948 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2023/d06/Day06.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d06
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.readLines
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.pow
import kotlin.math.sqrt
data class Race(val time: Long, val recordDistance: Long)
fun winningRange(race: Race): LongRange {
// the amount of time (s) to hold down the button to tie the record
// satisfies the equation -s^2 + st - r = 0
// where t is the race time, and r is the record distance
val t = race.time
val r = race.recordDistance
fun test(s: Long): Long = s * (t - s) - r
val discriminant = t.toDouble().pow(2) - 4 * r
val lowSolution = ceil((t - sqrt(discriminant)) / 2).toLong()
val highSolution = floor((t + sqrt(discriminant)) / 2).toLong()
// find integers that beat, not tie, the record, by starting with the approximate
// solutions and iterating until the best solution to the strict inequality is found
//
// for my input, this was unnecessary -- lowSolution and highSolution turned out to be the
// ideal solutions, so double precision arithmetic was good enough to get them on the first
// try. it is possible that other inputs would require this extra work though
val firstIntSolution =
if (test(lowSolution) <= 0) {
generateSequence(lowSolution) { it + 1 }
.first { test(it) > 0 }
} else {
generateSequence(lowSolution) { it - 1 }
.first { test(it - 1) <= 0 }
}
val lastIntSolution =
if (test(highSolution) <= 0) {
generateSequence(highSolution) { it - 1 }
.first { test(it) > 0 }
} else {
generateSequence(highSolution) { it + 1 }
.first { test(it + 1) <= 0 }
}
return firstIntSolution..lastIntSolution
}
fun main() = timed {
val races = (DATAPATH / "2023/day06.txt")
.readLines()
.map { line ->
line.split("""\s+""".toRegex())
.drop(1) // drop the prefix
.map(String::toLong)
}.let { (times, distances) ->
// there are exactly two rows, each with the same number of numbers
times.mapIndexed { i, time -> Race(time, distances[i]) }
}
races
.map(::winningRange)
.fold(1L) { p, winRange ->
p * (winRange.last - winRange.first + 1)
}
.also { println("Part one: $it") }
val combinedTime = races.map { it.time }.joinToString("").toLong()
val combinedRecord = races.map { it.recordDistance }.joinToString("").toLong()
winningRange(Race(combinedTime, combinedRecord))
.let { it.last - it.first + 1 }
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,818 | advent-of-code | MIT License |
src/day08/Day08.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day08
import readInput
const val day = "08"
fun main() {
fun calculatePart1Score(input: List<String>): Int {
val heightsHorizontal = input.map { it.toCharArray().map { char -> char.digitToInt() } }
val rows = heightsHorizontal.size
val columns = heightsHorizontal[0].size
val heightsVertical = heightsHorizontal.transpose()
check(rows == columns)
var visibleCount = 4 * (rows - 1)
(1 until rows - 1).forEach { row ->
(1 until columns - 1).forEach { column ->
val treeHeight = heightsHorizontal[row][column]
if (heightsHorizontal[row].subList(0, column).max() < treeHeight ||
heightsHorizontal[row].subList(column + 1, columns).max() < treeHeight ||
heightsVertical[column].subList(0, row).max() < treeHeight ||
heightsVertical[column].subList(row + 1, rows).max() < treeHeight
) {
visibleCount++
}
}
}
return visibleCount
}
fun calculatePart2Score(input: List<String>): Int {
val heightsHorizontal = input.map { it.toCharArray().map { char -> char.digitToInt() } }
val rows = heightsHorizontal.size
val columns = heightsHorizontal[0].size
val heightsVertical = heightsHorizontal.transpose()
check(rows == columns)
val scenicScores = Array(rows) { IntArray(columns) }
(1 until rows - 1).forEach { row ->
(1 until columns - 1).forEach { column ->
val treeHeight = heightsHorizontal[row][column]
val left = heightsHorizontal[row].subList(0, column)
.reversed()
.viewDistance(treeHeight)
val right = heightsHorizontal[row].subList(column + 1, columns)
.viewDistance(treeHeight)
val top = heightsVertical[column].subList(0, row)
.reversed()
.viewDistance(treeHeight)
val bottom = heightsVertical[column].subList(row + 1, rows)
.viewDistance(treeHeight)
scenicScores[row][column] = left * right * top * bottom
}
}
return scenicScores.maxOf { it.max() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
val part1Points = calculatePart1Score(input)
println("Part1 test points: $part1TestPoints")
println("Part1 points: $part1Points")
check(part1TestPoints == 21)
val part2TestPoints = calculatePart2Score(testInput)
val part2Points = calculatePart2Score(input)
println("Part2 test points: $part2TestPoints")
println("Part2 points: $part2Points")
check(part2TestPoints == 8)
}
fun <T> List<List<T>>.transpose(): List<List<T>> = List(first().size) { i ->
this.map { it[i] }
}
fun List<Int>.viewDistance(height: Int): Int {
val first = withIndex()
.firstOrNull { it.value >= height } ?: return this.size
return first
.index + 1
} | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 3,277 | advent-of-code-22-kotlin | Apache License 2.0 |
src/twentytwo/Day08.kt | mihainov | 573,105,304 | false | {"Kotlin": 42574} | package twentytwo
import readInputTwentyTwo
data class Visibility(
var fromTop: Boolean = false,
var fromLeft: Boolean = false,
var fromRight: Boolean = false,
var fromBot: Boolean = false
) {
fun isVisible(): Boolean {
return fromBot || fromLeft || fromRight || fromTop
}
}
fun ltrSeeker(treeRow: List<Int>, lolVisibility: List<List<Visibility>>, ri: Int) {
var currentHighest = -1
treeRow.forEachIndexed { ti, tree ->
if (tree > currentHighest) {
lolVisibility[ri][ti].fromLeft = true
currentHighest = tree
if (currentHighest == 9) {
return
}
}
}
}
fun rtlSeeker(treeRow: List<Int>, lolVisibility: List<List<Visibility>>, ri: Int) {
var currentHighest = -1
for (ti in 0..treeRow.lastIndex) {
val trueIndex = treeRow.lastIndex - ti
val tree = treeRow[trueIndex]
if (tree > currentHighest) {
lolVisibility[ri][trueIndex].fromRight = true
currentHighest = tree
if (currentHighest == 9) {
return
}
}
}
}
fun ttbSeeker(lolTree: List<List<Int>>, lolVisibility: List<List<Visibility>>, ci: Int) {
var currentHighest = -1
for (i in 0..lolTree.lastIndex) {
val tree = lolTree[i][ci]
if (tree > currentHighest) {
lolVisibility[i][ci].fromTop = true
currentHighest = tree
if (currentHighest == 9) {
return
}
}
}
}
fun bttSeeker(lolTree: List<List<Int>>, lolVisibility: List<List<Visibility>>, ci: Int) {
var currentHighest = -1
for (i in 0..lolTree.lastIndex) {
val trueIndex = lolTree.lastIndex - i
val tree = lolTree[trueIndex][ci]
if (tree > currentHighest) {
lolVisibility[trueIndex][ci].fromTop = true
currentHighest = tree
if (currentHighest == 9) {
return
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val lolTree = mutableListOf<List<Int>>()
input.forEach { treeRow -> lolTree.add(treeRow.toCharArray().map { it.digitToInt() }.toList()) }
val lolVisibility = List<List<Visibility>>(lolTree.size) {
List<Visibility>(lolTree.first().size) { Visibility() }
}
lolTree.forEachIndexed { ri, treeRow ->
ltrSeeker(treeRow, lolVisibility, ri)
rtlSeeker(treeRow, lolVisibility, ri)
}
for (i in 0..lolTree.first().lastIndex) {
ttbSeeker(lolTree, lolVisibility, i)
bttSeeker(lolTree, lolVisibility, i)
}
return lolVisibility.sumOf { it.count(Visibility::isVisible) }
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInputTwentyTwo("Day08_test")
check(part1(testInput).also(::println) == 21)
check(part2(testInput).also(::println) == 0)
val input = readInputTwentyTwo("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a9aae753cf97a8909656b6137918ed176a84765e | 3,147 | kotlin-aoc-1 | Apache License 2.0 |
src/main/kotlin/day07/Solution.kt | TestaDiRapa | 573,066,811 | false | {"Kotlin": 50405} | package day07
import java.io.File
import kotlin.system.measureTimeMillis
data class DirectoryTree (
val name: String,
val size: Int = 0,
val children: List<DirectoryTree> = listOf()
) {
val fullSize: Int by lazy { size + children.sumOf { it.fullSize } }
fun getDirectorySizeList(): List<Int> =
if (size == 0) {
listOf(fullSize) + children.flatMap { it.getDirectorySizeList() }
} else emptyList()
}
fun sumDirectoriesUnderSize(tree: DirectoryTree, maxSize: Int): Int
= (tree.fullSize.takeIf { it <= maxSize } ?: 0) + tree.children.filter { it.size == 0 }.sumOf { sumDirectoriesUnderSize(it, maxSize) }
fun findSmallerDirectoryToDelete(tree: DirectoryTree): Int {
val availableSpace = 70000000 - tree.fullSize
val neededSpace = 30000000 - availableSpace
assert(neededSpace > 0)
return tree.getDirectorySizeList().sorted().first { it >= neededSpace }
}
fun addToTreeAtNode(tree: DirectoryTree, levels: List<String>, size: Int, name: String): DirectoryTree {
return if (levels.isEmpty()) {
tree.copy(children = tree.children + DirectoryTree(name, size))
} else {
val nextLevel = levels.first()
val nextChild = tree.children.first { it.name == nextLevel }
tree.copy(children =
tree.children.filter{ it.name != nextLevel} + addToTreeAtNode(nextChild, levels.drop(1), size, name)
)
}
}
fun parseFileAndBuildTree() =
File("src/main/kotlin/day07/input.txt")
.readLines()
.fold(Pair(emptyList<String>(), DirectoryTree("/"))) { acc, it ->
if ( it.startsWith("$")) {
Regex("cd ([.a-z]+)").find(it)
?.groupValues
?.let {
if (it[1] == "..") {
Pair(
acc.first.dropLast(1),
acc.second
)
} else {
Pair(
acc.first + it[1],
acc.second
)
}
}?: acc
} else {
val (sizeType, fileName) = it.split(' ')
Pair(
acc.first,
addToTreeAtNode(
acc.second,
acc.first,
if (sizeType == "dir") 0 else sizeType.toInt(),
fileName
)
)
}
}.second
fun main() {
val elapsed = measureTimeMillis {
val tree = parseFileAndBuildTree()
println("The sum of the directory which size is under 100000 is ${sumDirectoriesUnderSize(tree, 100000)}")
println("The size of the smallest directory to delete is ${findSmallerDirectoryToDelete(tree)}")
}
println("The whole thing needed $elapsed to finish")
} | 0 | Kotlin | 0 | 0 | b5b7ebff71cf55fcc26192628738862b6918c879 | 2,988 | advent-of-code-2022 | MIT License |
src/year2023/Day6.kt | drademacher | 725,945,859 | false | {"Kotlin": 76037} | package year2023
import readLines
import kotlin.random.Random
fun main() {
val input = parseInput(readLines("2023", "day6"))
val testInput = parseInput(readLines("2023", "day6_test"))
check(part1(testInput) == 288)
println("Part 1:" + part1(input))
check(part2(testInput) == 71503)
println("Part 2:" + part2(input))
}
private fun parseInput(input: List<String>): List<String> {
return input
}
private fun part1(input: List<String>): Int {
val times = input[0].dropWhile { !it.isDigit() }.split(" ").filter { it != "" }.map { it.toInt() }
val distancesToBeat = input[1].dropWhile { !it.isDigit() }.split(" ").filter { it != "" }.map { it.toInt() }
var result = 1
for (i in times.indices) {
val time = times[i]
val distanceToBeat = distancesToBeat[i]
val distances =
(1..time)
.map { x -> (time - x) * x }
.filter { distance -> distance > distanceToBeat }
.size
result *= distances
}
return result
}
private fun part2(input: List<String>): Int {
val time = input[0].filter { it.isDigit() }.toLong()
val distanceToBeat = input[1].filter { it.isDigit() }.toLong()
return distancesOverThreshold(time, distanceToBeat).toInt()
}
private fun distancesOverThreshold(
time: Long,
distanceThreshold: Long,
): Long {
fun distance(x: Long) = (time - x) * x
fun distanceOverThreshold(x: Long) = distance(x) >= distanceThreshold
fun getRandomTimeOverThreshold(): Long {
var result: Long
val random = Random(0)
do {
result = random.nextLong(time - 1)
} while (distance(result) < distanceThreshold)
return result
}
fun binarySearchForBoundaryTime(
left: Long,
right: Long,
): Long {
if (right - left < 50L) {
return if (distanceOverThreshold(right)) {
(left..right).first { distanceOverThreshold(it) }
} else {
(left..right).last { distanceOverThreshold(it) }
}
}
val mid: Long = (left + right) / 2
return if (distanceOverThreshold(mid) != distanceOverThreshold(left)) {
binarySearchForBoundaryTime(left, mid - 1)
} else {
binarySearchForBoundaryTime(mid + 1, right)
}
}
val splitNumber = getRandomTimeOverThreshold()
return binarySearchForBoundaryTime(splitNumber, time - 1) - binarySearchForBoundaryTime(0, splitNumber) + 1
}
| 0 | Kotlin | 0 | 0 | 4c4cbf677d97cfe96264b922af6ae332b9044ba8 | 2,541 | advent_of_code | MIT License |
src/main/kotlin/day16/Tickets.kt | lukasz-marek | 317,632,409 | false | {"Kotlin": 172913} | package day16
data class ValidationRule(val name: String, val ranges: List<Pair<Int, Int>>)
data class Ticket(val numbers: List<Int>)
fun Ticket.invalidNumbers(rules: List<ValidationRule>): List<Int> =
numbers.filterNot { number -> rules.any { it.isSatisfied(number) } }
fun ValidationRule.isSatisfied(value: Int) = ranges.any { it.contains(value) }
fun Ticket.isValid(rules: List<ValidationRule>): Boolean = invalidNumbers(rules).isEmpty()
fun Ticket.rulesDescribingFields(rules: List<ValidationRule>): List<Set<ValidationRule>> {
val rulesForFields = mutableListOf<Set<ValidationRule>>()
for (number in numbers) {
val satisfiedRules = rules.asSequence().filter { it.isSatisfied(number) }.toSet()
rulesForFields.add(satisfiedRules)
}
return rulesForFields.toList()
}
fun List<List<Set<ValidationRule>>>.flattenByIntersecting(): List<Set<ValidationRule>> =
reduce { hypothesis, sample -> hypothesis.intersectPositionally(sample) }
private fun List<Set<ValidationRule>>.intersectPositionally(other: List<Set<ValidationRule>>): List<Set<ValidationRule>> =
this.zip(other).map { it.first.intersect(it.second) }
private fun Pair<Int, Int>.contains(value: Int): Boolean = value in first..second
private val rulePattern = Regex("^(.+): (\\d+)-(\\d+) or (\\d+)-(\\d+)$")
fun parseRule(rule: String): ValidationRule {
val parsed = rulePattern.matchEntire(rule.trim())
val (ruleName, range1Start, range1End, range2Start, range2End) = parsed!!.destructured
return ValidationRule(
ruleName,
listOf(Pair(range1Start.toInt(), range1End.toInt()), Pair(range2Start.toInt(), range2End.toInt()))
)
}
fun parseTicket(ticket: String): Ticket {
val numbers = ticket.split(",").map { it.trim().toInt() }
return Ticket(numbers)
}
fun identifyFields(tickets: List<Ticket>, rules: List<ValidationRule>): Map<String, Int> {
val hypotheses = tickets.filter { it.isValid(rules) }
.map { it.rulesDescribingFields(rules) }
.flattenByIntersecting()
.map { set -> set.map { it.name }.toSet() }
return inferFields(hypotheses)
}
private fun inferFields(knowledge: List<Set<String>>): Map<String, Int> {
val sorted = knowledge.withIndex()
.sortedBy { it.value.size }
.map { Pair(it.index, it.value.toMutableSet()) }
val alreadySeen = sorted.first().second
for ((_, hypothesis) in sorted.drop(1)) {
hypothesis.removeAll(alreadySeen)
alreadySeen.addAll(hypothesis)
check(hypothesis.size == 1) { "Ambiguous hypothesis $hypothesis" }
}
return sorted
.map { (index, value) -> value.map { it to index } }
.flatten()
.toMap()
} | 0 | Kotlin | 0 | 0 | a16e95841e9b8ff9156b54e74ace9ccf33e6f2a6 | 2,703 | aoc2020 | MIT License |
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day19/Day19.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2020.day19
import eu.janvdb.aocutil.kotlin.readGroupedLines
fun main() {
val groupedLines = readGroupedLines(2020, "input19b.txt")
val rules = groupedLines[0].map(::parseRule).map { Pair(it.ruleNumber, it) }.toMap()
val regexes = calculateRegexes(rules)
val regex = Regex("^" + regexes[0] + "$")
val messages = groupedLines[1]
println(messages.filter(regex::matches).count())
}
fun parseRule(rule: String): Rule {
val ruleParts = rule.split(": ")
val ruleNumber = ruleParts[0].toInt()
if (ruleParts[1][0] == '"') {
return SimpleRule(ruleNumber, ruleParts[1][1])
}
val groups = ruleParts[1].split(" | ")
val subRules = groups.map { it.split(" ").map(String::toInt) }
return ComplexRule(ruleNumber, subRules)
}
fun calculateRegexes(rules: Map<Int, Rule>): Map<Int, String> {
val regexes = mutableMapOf<Int, String>()
while (regexes.size != rules.size) {
for (rule in rules.values) {
if (regexes.containsKey(rule.ruleNumber)) continue
if (rule.canCalculateRegex(regexes)) {
regexes[rule.ruleNumber] = rule.asRegex(regexes)
}
}
}
return regexes
}
abstract class Rule(val ruleNumber: Int) {
abstract fun canCalculateRegex(regexes: Map<Int, String>): Boolean
abstract fun asRegex(regexes: Map<Int, String>): String
}
class SimpleRule(ruleNumber: Int, val matchingChar: Char) : Rule(ruleNumber) {
override fun canCalculateRegex(regexes: Map<Int, String>) = true
override fun asRegex(regexes: Map<Int, String>): String {
return "$matchingChar"
}
override fun toString(): String {
return "$ruleNumber: \"$matchingChar\""
}
}
class ComplexRule(ruleNumber: Int, val subRules: List<List<Int>>) : Rule(ruleNumber) {
override fun canCalculateRegex(regexes: Map<Int, String>): Boolean {
return subRules.asSequence().flatMap(List<Int>::asSequence).all(regexes::containsKey)
}
override fun asRegex(regexes: Map<Int, String>): String {
fun asRegex(ruleNumber: Int): String {
return regexes[ruleNumber]!!
}
fun asRegex(subRule: List<Int>): String {
return subRule.joinToString(separator = "", transform = ::asRegex)
}
if (subRules.size == 1) return asRegex(subRules[0])
return subRules.joinToString(separator = "|", prefix = "(", postfix = ")", transform = ::asRegex)
}
override fun toString(): String {
val ruleList = subRules.map { it.joinToString(separator = " ") }.joinToString(separator = " | ")
return "$ruleNumber: $ruleList"
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,430 | advent-of-code | Apache License 2.0 |
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day04.kt | JamJaws | 725,792,497 | false | {"Kotlin": 30656} | package com.jamjaws.adventofcode.xxiii.day
import com.jamjaws.adventofcode.xxiii.readInput
import kotlin.collections.Set
import kotlin.math.pow
class Day04 {
fun part1(text: List<String>): Int =
text.asSequence()
.map(::getMatches)
.map(Set<String>::size)
.map { 2.0.pow(it - 1).toInt() }
.sum()
fun part2(text: List<String>): Int {
val scratchcards = text.map { line ->
val cardId = Regex("\\d+").find(line)!!.value.toInt()
val matches = getMatches(line)
Scratchcard(cardId, (cardId + 1..(cardId + matches.size)).map { it })
}
return scratchcards.sumOf { instances(it, scratchcards) }
}
private fun getMatches(line: String) = line.substringAfter(":").split('|').map(Regex("\\d+")::findAll)
.map { it.flatMap(MatchResult::groupValues).toList() }
.let { (winningNumbers, elfNumbers) -> elfNumbers.intersect(winningNumbers) }
private fun instances(scratchcard: Scratchcard, scratchcards: List<Scratchcard>): Int =
scratchcards.filter { item -> item.copies.contains(scratchcard.card) }
.map { item -> instances(item, scratchcards) }
.takeIf(List<Int>::isNotEmpty)
?.sum()
?.let(1::plus)
?: 1
}
data class Scratchcard(val card: Int, val copies: List<Int>)
fun main() {
val answer1 = Day04().part1(readInput("Day04"))
println(answer1)
val answer2 = Day04().part2(readInput("Day04"))
println(answer2)
}
| 0 | Kotlin | 0 | 0 | e2683305d762e3d96500d7268e617891fa397e9b | 1,541 | advent-of-code-2023 | MIT License |
src/Day07.kt | kecolk | 572,819,860 | false | {"Kotlin": 22071} | sealed class FileSystemNode() {
data class File(val name: String, val size: Int) : FileSystemNode()
data class Directory(
val name: String,
val items: MutableList<FileSystemNode> = mutableListOf()
) : FileSystemNode() {
fun size(): Int {
return items.sumOf { item ->
when (item) {
is Directory -> item.size()
is File -> item.size
}
}
}
}
}
class Parser(val input: List<String>) {
private var currentIndex = 2
private val root = FileSystemNode.Directory("/")
fun parseStructure(): FileSystemNode {
parseNext(root)
return root
}
private fun parseNext(directory: FileSystemNode.Directory) {
while (currentIndex < input.size) {
val command = input[currentIndex]
val parts = command.split(" ")
when {
command == "$ cd .." -> return
command.startsWith("$ cd") -> {
directory.items.firstOrNull {
it is FileSystemNode.Directory && it.name == parts[2]
}?.let {
currentIndex += 1
parseNext(it as FileSystemNode.Directory)
}
}
command.startsWith("$") -> {}
command.isBlank() -> {}
parts[0] == "dir" -> directory.items.add(FileSystemNode.Directory(parts[1]))
else -> directory.items.add(FileSystemNode.File(parts[1], parts[0].toInt()))
}
currentIndex += 1
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val filesystem = Parser(input).parseStructure()
return filesystem.accumulateDirs(acc = 0) { item, acc ->
val size = item.size()
if (size <= 100000) size else 0
}
}
fun part2(input: List<String>): Int {
val filesystem: FileSystemNode.Directory = Parser(input).parseStructure() as FileSystemNode.Directory
val totalUsed = filesystem.size()
val toBeFreed = totalUsed - 40000000
var currentDirSize = totalUsed
filesystem.accumulateDirs(acc = 0) { item, _ ->
val size = item.size()
if(size in toBeFreed until currentDirSize) {
currentDirSize = size
}
0
}
return currentDirSize
}
val testInput = readTextInput("Day07_test")
val input = readTextInput("Day07")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
println(part1(input))
println(part2(input))
}
private fun FileSystemNode.accumulateDirs(
acc: Int,
onItem: (FileSystemNode.Directory, Int) -> Int
): Int {
var current = acc
if (this is FileSystemNode.Directory) {
current += onItem(this, acc)
this.items.forEach {
current += it.accumulateDirs(0, onItem)
}
}
return current
}
| 0 | Kotlin | 0 | 0 | 72b3680a146d9d05be4ee209d5ba93ae46a5cb13 | 3,038 | kotlin_aoc_22 | Apache License 2.0 |
src/Day07.kt | tigerxy | 575,114,927 | false | {"Kotlin": 21255} | import Line.*
private fun List<String>.isCommand(): Boolean = first() == "$"
fun main() {
fun part1(input: List<String>): Int {
return createTree(input)
.getFolderSizes()
.filter { it <= 100000 }
.sum()
}
fun part2(input: List<String>): Int {
val tree = createTree(input)
val hasToFreeUp = tree.size - 40000000
return tree
.getFolderSizes()
.filter { it >= hasToFreeUp }
.min()
}
val day = "07"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
println("part1_test=${part1(testInput)}")
println("part2_test=${part2(testInput)}")
val input = readInput("Day$day")
println("part1=${part1(input)}")
println("part2=${part2(input)}")
}
private fun createTree(input: List<String>): Node.Dir {
val root: Node.Dir = Node.Root()
var current: Node.Dir = root
input.map { it.split(' ') }
.map { it.parse() }
.forEach { line ->
when (line) {
is CdRoot -> current = root
is CdUp -> current = current.parent
is Cd -> current = current.getDir(line.name)
is Dir -> current.append(line)
is File -> current.append(line)
is Ls -> {}
is Command -> {}
is Output -> {}
}
}
return root
}
private fun List<String>.parse() =
when (get(0)) {
"$" -> when (get(1)) {
"ls" -> Ls
"cd" -> when (get(2)) {
"/" -> CdRoot
".." -> CdUp
else -> Cd(get(2))
}
else -> throw IllegalArgumentException()
}
"dir" -> Dir(get(1))
else -> File(get(0).toInt(), get(1))
}
private sealed interface Line {
interface Command : Line
object Ls : Command
object CdUp : Command
object CdRoot : Command
data class Cd(var name: String) : Command
interface Output : Line
data class Dir(val name: String) : Output
data class File(val size: Int, val name: String) : Output
}
private sealed interface Node {
val name: String
val size: Int
abstract class Dir : Node {
abstract val parent: Dir
private var content: List<Node> = emptyList()
override val size: Int
get() = content.sumOf { it.size }
fun append(file: Line.File) {
content += File(file.name, file.size)
}
fun append(dir: Line.Dir) {
content += Sub(dir.name, this)
}
fun getDir(name: String) = content
.filterIsInstance<Dir>()
.first { it.name == name }
fun getFolderSizes(): List<Int> =
content
.filterIsInstance<Dir>()
.flatMap { it.getFolderSizes() } +
content.sumOf { it.size }
fun getFoldersWithMaxSize(maxSize: Int): Int {
val sub: Int = content
.filterIsInstance<Dir>()
.sumOf { it.getFoldersWithMaxSize(maxSize) }
val thisSize = content.sumOf { it.size }
return if (thisSize <= maxSize) {
sub + thisSize
} else {
sub
}
}
}
data class Sub(override val name: String, override val parent: Dir) : Dir()
class Root : Dir() {
override val parent: Dir
get() = throw IllegalArgumentException()
override val name: String
get() = "/"
}
data class File(override val name: String, override val size: Int) : Node
} | 0 | Kotlin | 0 | 1 | d516a3b8516a37fbb261a551cffe44b939f81146 | 3,715 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day07.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | fun main() {
val totalSpace = 70_000_000
val requiredSpace = 30_000_000
fun buildFileTree(input: List<String>): Map<String, Dir> {
val fileTree = mutableMapOf<String, Dir>()
var currentDir = ""
fun MutableMap<String, Dir>.currentDir(): Dir = getValue(currentDir)
fun String.nestedDir(target: String) = when {
this == "/" -> "$this$target"
target == "/" -> target
else -> "$this/$target"
}
input.forEach { line ->
val args = line.split(" ")
val firstArg = args[0]
when {
firstArg == "$" -> when (args[1]) {
"cd" -> {
val target = args[2]
if (target == "..") {
currentDir = fileTree.currentDir().parent
} else {
val nestedDir = currentDir.nestedDir(target)
fileTree[nestedDir] = Dir(parent = currentDir)
currentDir = nestedDir
}
}
}
firstArg == "dir" -> {
fileTree.currentDir().children.add(currentDir.nestedDir(args[1]))
}
firstArg.toIntOrNull() != null -> {
fileTree.currentDir().size += firstArg.toInt()
}
}
}
return fileTree
}
fun part1(input: List<String>): Int {
val fileTree = buildFileTree(input)
fun Dir.totalSize(): Int = size + children.map(fileTree::getValue).sumOf(Dir::totalSize)
return fileTree.entries
.map { it.value.totalSize() }
.filter { it < 100_000 }
.sum()
}
fun part2(input: List<String>): Int {
val fileTree = buildFileTree(input)
fun Dir.totalSize(): Int = size + children.map(fileTree::getValue).sumOf(Dir::totalSize)
val availableSpace = totalSpace - fileTree.getValue("/").totalSize()
val spaceToFree = requiredSpace - availableSpace
return fileTree.entries
.map { it.value.totalSize() }
.filter { it >= spaceToFree }
.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private data class Dir(
val parent: String,
var size: Int = 0,
val children: MutableList<String> = mutableListOf(),
)
| 0 | Kotlin | 0 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 2,676 | aoc-2022 | Apache License 2.0 |
src/aoc2022/Day02.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2022
private enum class Game(val initScore: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
val whatDefeat: Game
get() = when (this) {
ROCK -> SCISSORS
SCISSORS -> PAPER
PAPER -> ROCK
}
}
private fun Game.canDefeat(other: Game): Boolean = this.whatDefeat == other
private fun Game.playWith(other: Game): Int = when {
this.canDefeat(other) -> 6
this == other -> 3
else -> 0
}
fun main() {
fun List<String>.scoreOfRounds(decideRespondGame: (Game, String) -> Game): Int = sumOf { round ->
val opponentGameMap = mapOf(
"A" to Game.ROCK, "B" to Game.PAPER, "C" to Game.SCISSORS,
)
val (opponentGame, myGame) = round.split(" ").let { (elfRound, myStrategy) ->
val opponentElfGame = opponentGameMap.getValue(elfRound)
return@let opponentElfGame to decideRespondGame(opponentElfGame, myStrategy)
}
return@sumOf myGame.initScore + myGame.playWith(opponentGame)
}
fun part1(input: List<String>): Int = input.scoreOfRounds { _, encryptedResponse ->
return@scoreOfRounds when (encryptedResponse) {
"X" -> Game.ROCK
"Y" -> Game.PAPER
else -> Game.SCISSORS
}
}
fun part2(input: List<String>): Int = input.scoreOfRounds { opponentGame, encryptedStrategy ->
return@scoreOfRounds when (encryptedStrategy) {
// should lose
"X" -> opponentGame.whatDefeat
// draw
"Y" -> opponentGame
// win
else -> Game.values().first { it != opponentGame && it != opponentGame.whatDefeat }
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput).also(::println) == 15)
check(part2(testInput).also(::println) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 2,001 | Kotlin-AOC-2023 | Apache License 2.0 |
src/day03/Task.kt | dniHze | 433,447,720 | false | {"Kotlin": 35403} | package day03
import readInput
import kotlin.math.pow
fun main() {
val input = readInput("Day03")
println(solvePartOne(input))
println(solvePartTwo(input))
}
fun solvePartOne(input: List<String>): Int {
val counterArray = IntArray(input.first().length) { 0 }
input.onEach { value ->
value.reversed().forEachIndexed { index, char ->
if (char == '1') {
counterArray[index] += 1
}
}
}
var gamma = 0
var epsilon = 0
counterArray.forEachIndexed { index, count ->
val positive = (count * 2) > input.size
if (positive) {
gamma += (2.0).pow(index).toInt()
} else {
epsilon += (2.0).pow(index).toInt()
}
}
return gamma * epsilon
}
fun solvePartTwo(input: List<String>): Int {
val testTree = input.toWeightedTree()
val scrubberRating = testTree.findSmallestNode()
val generatorRating = testTree.findBiggestNode()
return scrubberRating * generatorRating
}
private fun List<String>.toWeightedTree(): TreeNode {
val tree = TreeNode(parent = null, value = "")
onEach { item ->
var node = tree
item.forEach { char ->
node = if (char == '1') node.right else node.left
}
node.increaseWeight()
}
return tree
}
private fun TreeNode.findBiggestNode(): Int {
var node = this
var binaryString = ""
while (node.biggest != null) {
node = node.biggest!!
binaryString += node.value
}
return binaryString.toInt(2)
}
private fun TreeNode.findSmallestNode(): Int {
var node = this
var binaryString = ""
while (node.smallest != null) {
node = node.smallest!!
binaryString += node.value
}
return binaryString.toInt(2)
}
data class TreeNode(
val value: String,
val parent: TreeNode?,
) {
private var weight = 0
val left by lazy { TreeNode(value = "0", parent = this) }
val right by lazy { TreeNode(value = "1", parent = this) }
val smallest: TreeNode?
get() = when {
left.weight == 0 && right.weight == 0 -> null
left.weight == 0 -> right
right.weight == 0 -> left
left <= right -> left
else -> right
}
val biggest: TreeNode?
get() = when {
left.weight == 0 && right.weight == 0 -> null
left.weight == 0 -> right
right.weight == 0 -> left
right >= left -> right
else -> left
}
operator fun compareTo(other: TreeNode) = weight.compareTo(other.weight)
fun increaseWeight() {
weight++
parent?.increaseWeight()
}
}
| 0 | Kotlin | 0 | 1 | f81794bd57abf513d129e63787bdf2a7a21fa0d3 | 2,704 | aoc-2021 | Apache License 2.0 |
src/main/kotlin/y2023/Day3.kt | juschmitt | 725,529,913 | false | {"Kotlin": 18866} | package y2023
import utils.Day
class Day3 : Day(3, 2023, false) {
override fun partOne(): Any {
return inputList.mapToSchema().numbersWithAdjacentSymbol().sumOf { it.value }
}
override fun partTwo(): Any {
return inputList.mapToSchema().findGearRatios().sum()
}
}
private fun Map<Int, List<Schema>>.findGearRatios(): List<Int> = map { entry ->
entry.value.filter { schema -> schema is Schema.Symbol && schema.isGear(this, entry.key) }
.mapNotNull { schema -> (schema as? Schema.Symbol)?.getAdjacentNumbers(this, entry.key) }
.map { it.first().value * it.last().value }
}.flatten()
private fun Schema.Symbol.isGear(schemaMap: Map<Int, List<Schema>>, lineIdx: Int): Boolean =
symbol == "*" && getAdjacentNumbers(schemaMap, lineIdx).size == 2
private fun Schema.Symbol.getAdjacentNumbers(schemaMap: Map<Int, List<Schema>>, lineIdx: Int): List<Schema.Number> =
schemaMap.getSurroundingLines(lineIdx)
.filterInRange { this.index in it.startIndex-1..it.endIndex+1 }
private fun Map<Int, List<Schema>>.numbersWithAdjacentSymbol(): List<Schema.Number> = map { entry ->
entry.value.filter { schema -> schema is Schema.Number && schema.hasAdjacentSymbol(this, entry.key) }
.mapNotNull { it as? Schema.Number }
}.flatten()
private fun Schema.Number.hasAdjacentSymbol(schemaMap: Map<Int, List<Schema>>, lineIdx: Int): Boolean =
schemaMap.getSurroundingLines(lineIdx)
.filterInRange<Schema.Symbol> { it.index in this.startIndex-1..this.endIndex+1 }.isNotEmpty()
private inline fun <reified T : Schema> List<Schema>.filterInRange(filter: (T) -> Boolean): List<T> =
filterIsInstance<T>().filter(filter)
private fun Map<Int, List<Schema>>.getSurroundingLines(lineIdx: Int): List<Schema> =
getOrDefault(lineIdx, emptyList()) +
getOrDefault(lineIdx+1, emptyList()) +
getOrDefault(lineIdx-1, emptyList())
private fun List<String>.mapToSchema(): Map<Int, List<Schema>> = mapIndexed { index, line ->
val symbols: List<Schema.Symbol> = line.mapIndexedNotNull { i, c ->
if (c != '.' && !c.isDigit()) Schema.Symbol(i, c.toString()) else null
}
val numbers: List<Schema.Number> = line.foldIndexed(emptyList()) { i, acc, char ->
when {
char.isDigit() && line.getOrNull(i-1)?.isDigit() == true -> {
val last = acc.last()
acc.dropLast(1) + last.copy(endIndex = i, value = last.value*10 + char.digitToInt())
}
char.isDigit() -> acc + Schema.Number(i, i, char.digitToInt())
else -> acc
}
}
index to symbols + numbers
}.toMap()
private sealed interface Schema {
data class Number(val startIndex: Int, val endIndex: Int, val value: Int) : Schema
data class Symbol(val index: Int, val symbol: String) : Schema
} | 0 | Kotlin | 0 | 0 | b1db7b8e9f1037d4c16e6b733145da7ad807b40a | 2,847 | adventofcode | MIT License |
src/main/kotlin/aoc22/Day08.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc22
import common.Collections.product
import aoc22.Day08Solution.visibleTreeCount
import aoc22.Day08Solution.maxScenicScore
import common.Space2D.Point
import common.Space2D.Parser.toPointToChars
import common.Year22
object Day08: Year22 {
fun List<String>.part1(): Int = visibleTreeCount()
fun List<String>.part2(): Int = maxScenicScore()
}
object Day08Solution {
fun List<String>.visibleTreeCount(): Int =
toTrees().run {
count { tree ->
viewsFor(tree).any { it.edgeIsVisibleFrom(tree) }
}
}
private fun List<Tree>.edgeIsVisibleFrom(tree: Tree): Boolean = isEmpty() || all { it.height < tree.height }
fun List<String>.maxScenicScore(): Int =
toTrees().run {
maxOf { tree ->
viewsFor(tree).map { it.viewingDistanceFor(tree) }.product()
}
}
private fun List<Tree>.viewingDistanceFor(tree: Tree): Int {
val tallerTreesInView = filter { it.height >= tree.height }
return when {
isEmpty() -> 0
tallerTreesInView.isEmpty() -> size
else -> tallerTreesInView.minOf { tree.point.distanceTo(it.point) }
}
}
private fun List<String>.toTrees(): List<Tree> =
toPointToChars()
.map { (p, c) -> Tree(p, c.digitToInt()) }
private data class Tree(
val point: Point,
val height: Int,
)
private fun List<Tree>.viewsFor(tree: Tree): List<List<Tree>> {
fun Tree.x(): Int = this.point.x
fun Tree.y(): Int = this.point.y
return listOf(
filter { it.x() == tree.x() && it.y() > tree.y() },
filter { it.x() == tree.x() && it.y() < tree.y() },
filter { it.y() == tree.y() && it.x() > tree.x() },
filter { it.y() == tree.y() && it.x() < tree.x() },
)
}
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 1,927 | aoc | Apache License 2.0 |
src/day19/Day19.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day19
import java.io.File
fun main() {
val (workflows, parts) = parse("src/day19/Day19.txt")
println("🎄 Day 19 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(workflows, parts)}")
println()
println("[Part 2]")
println("Answer: ${part2(workflows)}")
}
private data class Condition(
val key: Char,
val cmp: Char,
val num: Int,
)
private data class Rule(
val condition: Condition?,
val transition: String,
)
private typealias Part = Map<Char, Int>
private typealias Workflows = Map<String, List<Rule>>
private fun String.toPart(): Part =
this.trim('{', '}')
.split(',')
.map { it.split('=') }
.associate { (k, n) -> k.first() to n.toInt() }
private fun String.toRule(): Rule {
if (!this.contains(':')) {
return Rule(condition = null, transition = this)
}
val (lhs, transition) = this.split(':')
val condition = Condition(
key = lhs[0],
cmp = lhs[1],
num = lhs.substring(2).toInt(),
)
return Rule(condition, transition)
}
private fun String.toWorkflow(): Pair<String, List<Rule>> {
val (name, rules) = this.trim('}').split('{')
return Pair(name, rules.split(',').map(String::toRule))
}
private fun parse(path: String): Pair<Workflows, List<Part>> {
val (workflowsPart, partsPart) = File(path)
.readText()
.split("\n\n", "\r\n\r\n")
val workflows = workflowsPart.lines()
.map(String::toWorkflow)
.associate { (name, rules) -> name to rules }
val parts = partsPart.lines()
.map(String::toPart)
return Pair(workflows, parts)
}
private fun count(part: Part, workflows: Workflows): Int {
var target = "in"
while (target != "A" && target != "R") {
val rules = workflows.getValue(target)
for ((condition, transition) in rules) {
if (condition == null) {
target = transition
break
}
val (key, cmp, num) = condition
val satisfies = if (cmp == '>') {
part.getValue(key) > num
} else {
part.getValue(key) < num
}
if (satisfies) {
target = transition
break
}
}
}
return if (target == "A") {
part.values.sum()
} else {
0
}
}
private fun part1(workflows: Workflows, parts: List<Part>): Int =
parts.sumOf { count(it, workflows) }
private fun part2(workflows: Workflows): Long {
val queue = ArrayDeque<Pair<String, Map<Char, IntRange>>>()
.apply { add("in" to mapOf(
'x' to 1..4000,
'm' to 1..4000,
'a' to 1..4000,
's' to 1..4000,
)) }
var total = 0L
while (queue.isNotEmpty()) {
val (target, startingRanges) = queue.removeFirst()
if (target == "A" || target == "R") {
if (target == "A") {
val product = startingRanges.values
.map { (it.last - it.first + 1).toLong() }
.reduce { acc, it -> acc * it }
total += product
}
continue
}
val ranges = startingRanges.toMutableMap()
val rules = workflows.getValue(target)
for ((condition, transition) in rules) {
if (condition == null) {
queue += transition to ranges
break
}
val (key, cmp, num) = condition
val range = ranges.getValue(key)
val (t, f) = if (cmp == '>') {
IntRange(num + 1, range.last) to IntRange(range.first, num)
} else {
IntRange(range.first, num - 1) to IntRange(num, range.last)
}
queue += transition to ranges.toMutableMap().apply { set(key, t) }
ranges[key] = f
}
}
return total
}
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 4,119 | advent-of-code-2023 | MIT License |
app/src/main/kotlin/day05/Day05.kt | KingOfDog | 433,706,881 | false | {"Kotlin": 76907} | package day05
import common.InputRepo
import common.readSessionCookie
import common.solve
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
fun main(args: Array<String>) {
val day = 5
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay05Part1, ::solveDay05Part2)
}
fun solveDay05Part1(input: List<String>): Int {
val lines = parseInput(input)
val points = mutableMapOf<Point, Int>()
lines
.filterNot { it.isDiagonal }
.forEach { line ->
for (i in 0..line.distance) {
val point = line.getPointAt(i)
points[point] = points.getOrDefault(point, 0) + 1
}
}
return points.countDuplicates()
}
fun solveDay05Part2(input: List<String>): Int {
val lines = parseInput(input)
val points = mutableMapOf<Point, Int>()
lines.forEach { line ->
for (i in 0..line.distance) {
val point = line.getPointAt(i)
points[point] = points.getOrDefault(point, 0) + 1
}
}
return points.countDuplicates()
}
private fun Map<Point, Int>.countDuplicates() = filterValues { it > 1 }.count()
private fun parseInput(input: List<String>): List<day05.Line> {
val regex = Regex("(\\d+),(\\d+) -> (\\d+),(\\d+)")
return input.map { regex.find(it)!!.groupValues }
.map { values -> values.subList(1, values.size).map { it.toInt() } }
.map { numbers -> Line(Point(numbers[0], numbers[1]), Point(numbers[2], numbers[3])) }
}
data class Point(val x: Int, val y: Int)
data class Line(val a: Point, val b: Point) {
val isHorizontal: Boolean get() = a.y == b.y
val isVertical: Boolean get() = a.x == b.x
val isDiagonal: Boolean get() = !isHorizontal && !isVertical
val distance: Int get() = max(abs(a.x - b.x), abs(a.y - b.y))
fun getPointAt(pos: Int): Point {
val x = lerp(a.x.toDouble(), b.x.toDouble(), pos / distance.toDouble()).roundToInt()
val y = lerp(a.y.toDouble(), b.y.toDouble(), pos / distance.toDouble()).roundToInt()
return Point(x, y)
}
}
private fun lerp(x: Double, y: Double, t: Double): Double {
return x * (1 - t) + y * t
}
| 0 | Kotlin | 0 | 0 | 576e5599ada224e5cf21ccf20757673ca6f8310a | 2,223 | advent-of-code-kt | Apache License 2.0 |
src/main/kotlin/aoc2022/Day02.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import readInput
import java.lang.IllegalArgumentException
enum class Shape(val value: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
companion object {
fun fromChar(char: Char) = when (char) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> throw IllegalArgumentException("Unknown shape: $char")
}
}
}
enum class Result(val value: Int) {
WIN(6), DRAW(3), LOSS(0);
companion object {
fun fromChar(char: Char) = when (char) {
'X' -> LOSS
'Y' -> DRAW
'Z' -> WIN
else -> throw IllegalArgumentException("Unknown result: $char")
}
}
}
fun main() {
fun play(opponent: Shape, myself: Shape) = when {
opponent == Shape.ROCK && myself == Shape.PAPER -> Result.WIN
opponent == Shape.ROCK && myself == Shape.SCISSORS -> Result.LOSS
opponent == Shape.PAPER && myself == Shape.ROCK -> Result.LOSS
opponent == Shape.PAPER && myself == Shape.SCISSORS -> Result.WIN
opponent == Shape.SCISSORS && myself == Shape.ROCK -> Result.WIN
opponent == Shape.SCISSORS && myself == Shape.PAPER -> Result.LOSS
else -> Result.DRAW
}
fun findShape(opponent: Shape, expectedResult: Result) = when {
opponent == Shape.ROCK && expectedResult == Result.WIN -> Shape.PAPER
opponent == Shape.ROCK && expectedResult == Result.LOSS -> Shape.SCISSORS
opponent == Shape.PAPER && expectedResult == Result.WIN -> Shape.SCISSORS
opponent == Shape.PAPER && expectedResult == Result.LOSS -> Shape.ROCK
opponent == Shape.SCISSORS && expectedResult == Result.WIN -> Shape.ROCK
opponent == Shape.SCISSORS && expectedResult == Result.LOSS -> Shape.PAPER
else -> opponent // draw
}
fun part1(input: List<String>): Int {
val rounds = input.map {
val (p0, p1) = it.split(" ", limit = 2).map { str -> Shape.fromChar(str.toCharArray().first()) }
val result = play(p0, p1)
result.value + p1.value
}
return rounds.sum()
}
fun part2(input: List<String>): Int {
val rounds = input.map {
val round = it.split(" ", limit = 2)
val opponentShape = Shape.fromChar(round[0].toCharArray().first())
val expectedResult = Result.fromChar(round[1].toCharArray().first())
val myShape = findShape(opponentShape, expectedResult)
expectedResult.value + myShape.value
}
return rounds.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test", 2022)
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02", 2022)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 2,880 | adventOfCode | Apache License 2.0 |
src/Day04.kt | anisch | 573,147,806 | false | {"Kotlin": 38951} | fun inRange(a: Int, b: Int, c: Int, d: Int): Boolean =
(c <= a && b <= d) || (a <= c && d <= b)
fun overlaps(a: Int, b: Int, c: Int, d: Int): Boolean =
(a in c..d) || (b in c..d) || (c in a..b) || (d in a..b)
fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.split(",") }
.map { (f, s) ->
val (a, b) = f.split("-")
val (c, d) = s.split("-")
inRange(a.toInt(), b.toInt(), c.toInt(), d.toInt())
}
.count { it }
}
fun part2(input: List<String>): Int {
return input
.map { it.split(",") }
.map { (f, s) ->
val (a, b) = f.split("-")
val (c, d) = s.split("-")
overlaps(a.toInt(), b.toInt(), c.toInt(), d.toInt())
}
.count { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val input = readInput("Day04")
check(part1(testInput) == 2)
println(part1(input))
check(part2(testInput) == 4)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f45d264d578661957800cb01d63b6c7c00f97b1 | 1,198 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day05.kt | mkfsn | 573,042,358 | false | {"Kotlin": 29625} | import java.util.Stack
fun main() {
class Solution(input: List<String>) {
val supplyStacks: List<Stack<String>>
val procedures: List<String>
init {
val (spec, procedures) = input.chunkedBy { ele -> ele == "" };
val (indexes, configurations) = spec.asReversed().run { Pair(this.first(), this.drop(1)) }
this.supplyStacks = indexes.toNumbers().map { Stack<String>() }
this.procedures = procedures
configurations.forEach { row ->
row.chunked(4).map { it.replace(" ", "") }.forEachIndexed { i, v ->
if (v != "") this.supplyStacks[i].push(v.trim('[', ']'))
}
}
}
fun moveCrates(executor: (count: Int, from: Int, to: Int, stacks: List<Stack<String>>) -> Unit) = apply {
procedures.forEach { procedure ->
val (count, from, to) = procedure.toNumbers()
executor(count, from, to, this.supplyStacks)
}
}
fun toResult(): String = supplyStacks.joinToString(separator = "") { if (it.size == 0) "_" else it.last() }
}
fun part1(input: List<String>): String =
Solution(input).moveCrates { count: Int, from: Int, to: Int, stacks: List<Stack<String>> ->
(1..count).forEach { _ -> stacks[to - 1].push(stacks[from - 1].pop()) }
}.toResult()
fun part2(input: List<String>): String =
Solution(input).moveCrates { count: Int, from: Int, to: Int, stacks: List<Stack<String>> ->
val tmpStack = Stack<String>()
(1..count).forEach { _ -> tmpStack.push(stacks[from - 1].pop()) }
(1..count).forEach { _ -> stacks[to - 1].push(tmpStack.pop()) }
}.toResult()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 8c7bdd66f8550a82030127aa36c2a6a4262592cd | 2,050 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day15.kt | mikrise2 | 573,939,318 | false | {"Kotlin": 62406} | import kotlin.math.abs
import kotlin.math.absoluteValue
class UnRange constructor(private var list: List<IntRange>) {
constructor(r: IntRange) : this(listOf(r))
fun minus(s: IntRange): UnRange {
if (s.isEmpty()) {
return this
}
val ranges = ArrayList<IntRange>(list.size + 2)
list.forEachIndexed {index, range->
val end = s.last + 1
val start = s.first - 1
if (range.contains(start) || range.contains(end)) {
if (range.contains(start)) {
ranges.add(range.first..start)
}
if (range.contains(end)) {
ranges.add(end..range.last)
}
} else if (!s.contains(range.first) || !s.contains(range.last)) {
ranges.add(range)
}
}
list = ranges
return this
}
fun first() = list.first().first
fun sum() = list.sumOf { it.last - it.first + 1 }
}
operator fun Pair<Int, Int>.minus(other: Pair<Int, Int>) =
abs(this.first - other.first) + abs(this.second - other.second)
fun main() {
fun part1(input: List<String>): Int {
val sensors = input.map {
val split = it.split(" ")
val xS = split[2].substring(2, split[2].lastIndex).toInt()
val yS = split[3].substring(2, split[3].lastIndex).toInt()
val xB = split[8].substring(2, split[8].lastIndex).toInt()
val yB = split[9].substring(2, split[9].length).toInt()
listOf(Pair(xS, yS), Pair(xB, yB))
}
val map = mutableSetOf<Int>()
sensors.forEach {
val distance = it[0] - it[1]
val remainder = distance - kotlin.math.abs(it[0].second - 2000000)
if (remainder > 0) {
map += (it[0].first..(it[0].first + remainder)).toSet()
map += (it[0].first downTo (it[0].first - remainder)).toSet()
}
}
return map.minus(sensors.filter { it[1].second == 2000000 }.map { it[1].first }.toSet()).size
}
fun coveredRange(point: Pair<Int, Int>, radius: Int, targetY: Int): IntRange? {
val yOff = (targetY - point.second).absoluteValue
val rowRadius = radius - yOff
return if (yOff > radius) {
null
} else {
point.first - rowRadius..point.first + rowRadius
}
}
fun part2(input: List<String>): Long {
val sensors = input.map {
val split = it.split(" ")
val xS = split[2].substring(2, split[2].lastIndex).toInt()
val yS = split[3].substring(2, split[3].lastIndex).toInt()
val xB = split[8].substring(2, split[8].lastIndex).toInt()
val yB = split[9].substring(2, split[9].length).toInt()
listOf(Pair(xS, yS), Pair(xB, yB))
}
var expectedX: Int? = null
var expectedY: Int? = null
val range = 0..4000000
for (y in range) {
val expected = UnRange(range)
for ((s, b) in sensors) {
val coveredRange = coveredRange(s, s-b, y)
if (coveredRange != null) {
expected.minus(coveredRange)
}
}
val count = expected.sum()
if (count == 1) {
expectedY = y
expectedX = expected.first()
break
}
}
return expectedX!! * 4000000L + expectedY!!
}
val input = readInput("Day15")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8 | 3,603 | Advent-of-code | Apache License 2.0 |
Advent-of-Code-2023/src/Day12.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day12"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
/**
* Hashmap used for memoization, to avoid recalculating the same values.
*/
private val cache = hashMapOf<Pair<String, List<Int>>, Long>()
fun count(springs: String, springsSize: List<Int>): Long {
if (springs == "") return if (springsSize.isEmpty()) 1 else 0
if (springsSize.isEmpty()) return if (springs.contains("#")) 0 else 1
val pair = Pair(springs, springsSize)
if (pair in cache) return cache[pair]!!
var count = 0L
if (springs[0] in ".?") {
count += count(springs.substring(1), springsSize)
}
if (springs[0] in "#?") {
if (springsSize[0] <= springs.length && "." !in springs.substring(0, springsSize[0]) &&
(springsSize[0] == springs.length || springs[springsSize[0]] != '#'))
{
val subSpring = if (springsSize[0] + 1 >= springs.length) "" else springs.substring(springsSize[0] + 1)
count += count(subSpring, springsSize.drop(1))
}
}
cache[pair] = count
return count
}
private fun part1(input: List<String>): Long {
val parsedInput = input.map { it.split(" ") }
val springs = parsedInput.map { it.first() }
val springsSize = parsedInput.map { it.last().split(",").map { num -> num.toInt() } }
return springsSize.zip(springs).sumOf { (size, spring) -> count(spring, size) }
}
private fun part2(input: List<String>): Long {
val parsedInput = input.map { it.split(" ") }
val springs = parsedInput.map { "${it.first()}?".repeat(5) }.map { it.dropLast(1) }
val springsSize = parsedInput.map { "${it.last()},".repeat(5).split(",").dropLast(1).map { num -> num.toInt() } }
return springsSize.zip(springs).sumOf { (size, spring) -> count(spring, size) }
}
fun main() {
createTestFiles(AOC_DAY)
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 21
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 525152
println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 7771" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 10861030975833" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 2,445 | Advent-of-Code-2023 | Apache License 2.0 |
src/Day02.kt | EemeliHeinonen | 574,062,219 | false | {"Kotlin": 6073} | import Choice.*
import Result.*
enum class Choice(val firstLetter: Char, val secondLetter: Char, val points: Int) {
ROCK('A', 'X', 1),
PAPER('B', 'Y', 2),
SCISSORS('C', 'Z', 3);
companion object {
infix fun fromFirstLetter(firstLetter: Char): Choice = values().first { it.firstLetter == firstLetter }
infix fun fromSecondLetter(secondLetter: Char): Choice = values().first { it.secondLetter == secondLetter }
}
}
enum class Result(val letter: Char, val points: Int) {
LOSE('X',0),
DRAW('Y',3),
WIN('Z',6);
companion object {
infix fun fromLetter(letter: Char): Result = values().first { it.letter == letter }
}
}
fun getPointsForRoundByPlayerChoice(firstLetter: Char, secondLetter: Char): Int {
val opponentChoice = Choice.fromFirstLetter(firstLetter)
val playerChoice = Choice.fromSecondLetter(secondLetter)
val choicePoints = playerChoice.points
return if (playerChoice == opponentChoice) {
DRAW.points + choicePoints
} else if ((playerChoice == ROCK && opponentChoice == SCISSORS) ||
(playerChoice == PAPER && opponentChoice == ROCK) ||
(playerChoice == SCISSORS && opponentChoice == PAPER)) {
WIN.points + choicePoints
} else {
LOSE.points + choicePoints
}
}
fun getPointsForRoundByResult(firstLetter: Char, secondLetter: Char): Int {
val opponentChoice = Choice.fromFirstLetter(firstLetter)
val result = Result.fromLetter(secondLetter)
val playerChoice = when (result) {
DRAW -> opponentChoice
WIN -> when (opponentChoice) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
LOSE -> when (opponentChoice) {
SCISSORS -> PAPER
ROCK -> SCISSORS
PAPER -> ROCK
}
}
return result.points + playerChoice.points
}
fun CharArray.firstAndLast() = Pair(this.first(), this.last())
fun calculatePoints(input: List<String>, calculationFn: (Char, Char) -> Int) = input.fold(0) { total, currentString ->
val (firstLetter, secondLetter) = currentString.toCharArray().firstAndLast()
val pointsForRound = calculationFn(firstLetter, secondLetter)
total + pointsForRound
}
fun main() {
fun part1(input: List<String>): Int {
return calculatePoints(input, ::getPointsForRoundByPlayerChoice)
}
fun part2(input: List<String>): Int {
return calculatePoints(input, ::getPointsForRoundByResult)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
println(part1(testInput))
check(part2(testInput) == 12)
println(part2(testInput))
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 33775d9e6e848ab0efae0e3f00f43368c036799d | 2,845 | aoc-22-kotlin | Apache License 2.0 |
src/main/kotlin/days/y2023/day12/Day12.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2023.day12
import util.InputReader
typealias PuzzleLine = String
typealias PuzzleInput = List<PuzzleLine>
class Day12(val input: PuzzleInput) {
fun partOne(): Int {
return input.sumOf { line -> line.toConfiguration().arrangements().size }
}
fun partTwo(): Int {
val bigInput = input.map { line -> line.toConfiguration().bigify(5) }
return bigInput.sumOf { line -> line.arrangements().size }
}
}
data class Configuration(
val str: String,
val widths: List<Int>
)
fun PuzzleLine.toConfiguration(): Configuration {
val (head, blocks) = this.split(" ")
return Configuration(head.chompDots(), blocks.split(",").map { it.toInt() })
}
fun String.chompDots(): String {
return this.replace(Regex("\\.+"), ".")
}
fun Configuration.arrangements(): Set<Configuration> {
if (!potentiallyValid()) {
return emptySet()
}
if (!this.str.contains('?')) {
return setOf(this)
}
val left = copy(str = str.replaceFirst('?', '.')).arrangements()
val right = copy(str = str.replaceFirst('?', '#')).arrangements()
return left + right
}
fun Configuration.potentiallyValid(): Boolean {
val islands = this.str.split('.').filter { it.isNotEmpty() }
val actual = islands.mapNotNull { it.takeIf { !it.contains('?') }?.length }
if (!this.str.contains('?')) return actual == widths
if (actual.size > widths.size) return false
// the elements in actual must appear in the right order in expected
var i = 0
var j = 0
while (i < actual.size && j < widths.size) {
val a = actual[i]
val b = widths[j]
if (a == b) {
i++
j++
} else {
j++
}
}
return i == actual.size
}
fun Configuration.bigify(n: Int) = copy(
str = List(n) { this.str }.joinToString("?"),
widths = List(n) { this.widths }.flatten()
)
fun main() {
val year = 2023
val day = 12
val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day)
val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day)
fun partOne(input: PuzzleInput) = Day12(input).partOne()
fun partTwo(input: PuzzleInput) = Day12(input).partTwo()
println("Example 1: ${partOne(exampleInput)}")
println("Puzzle 1: ${partOne(puzzleInput)}")
println("Example 2: ${partTwo(exampleInput)}")
println("Puzzle 2: ${partTwo(puzzleInput)}")
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 2,442 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/y2023/Day04.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2023
import util.readInput
import util.timingStatistics
import kotlin.math.pow
object Day04 {
private fun parse(input: List<String>): List<Pair<List<Int>, List<Int>>> {
return input.map { line ->
val (winning, mine) = line.substringAfter(":").trim().split(" | ")
winning.split(" ").mapNotNull { it.toIntOrNull() } to mine.split(" ").mapNotNull { it.toIntOrNull() }
}
}
fun part1(input: List<String>): Double {
val parsed = parse(input)
return parsed.map { (winning, mine) ->
mine.filter { it in winning }.size
}.filter { it != 0 }.sumOf { 2.0.pow(it - 1) }
}
fun part2(input: List<String>): Int {
val parsed = parse(input)
val numberWonByCard = parsed.map { (winning, mine) ->
mine.filter { it in winning }.size
}
val numberCards = MutableList(numberWonByCard.size) { 1 }
numberWonByCard.mapIndexed { index, thisWin ->
(1..thisWin).forEach {
numberCards[index + it] += numberCards[index]
}
}
return numberCards.sum()
}
}
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")
println("------Tests------")
println(Day04.part1(testInput))
println(Day04.part2(testInput))
println("------Real------")
val input = readInput("resources/2023/day04")
println("Part 1 result: ${Day04.part1(input)}")
println("Part 2 result: ${Day04.part2(input)}")
timingStatistics { Day04.part1(input) }
timingStatistics { Day04.part2(input) }
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,937 | advent-of-code | Apache License 2.0 |
src/Day03.kt | Oli2861 | 572,895,182 | false | {"Kotlin": 16729} | fun toCompartments(rucksack: String): Pair<String, String> {
val length = rucksack.length
val middle = length / 2
return Pair(rucksack.substring(0, middle), rucksack.substring(middle, length))
}
fun getPriority(char: Char) =
if (char.isUpperCase()) char.lowercaseChar().code - 64 - 6 else char.uppercaseChar().code - 64
fun findMatches(compartments: Pair<String, String>) = findMatches(compartments.first, compartments.second)
fun findMatches(compartment: String, compartment1: String): List<Char> =
compartment.toCharArray().toList().filter { compartment1.contains(it) }
fun getMaxPrioMatch(rucksack: String): Int {
val compartments = toCompartments(rucksack)
return findMatches(compartments).maxOf { getPriority(it) }
}
fun getMaxPrioMatchSum(rucksacks: List<String>): Int = rucksacks.sumOf { getMaxPrioMatch(it) }
fun getBatch(rucksack: String, rucksack1: String, rucksack2: String): Char =
rucksack.toCharArray().toList().first { rucksack1.contains(it) && rucksack2.contains(it) }
fun getBatchSum(rucksacks: List<String>): Int {
var sum = 0
for (index in 2..rucksacks.size step 3) {
sum += getPriority(getBatch(rucksacks[index - 2], rucksacks[index - 1], rucksacks[index]))
}
return sum
}
fun main() {
val input = readInput("Day03_text")
val result = getMaxPrioMatchSum(input)
println(result)
check(result == 7889)
val result2 = getBatchSum(input)
println(result2)
check(result2 == 2825)
} | 0 | Kotlin | 0 | 0 | 138b79001245ec221d8df2a6db0aaeb131725af2 | 1,487 | Advent-of-Code-2022 | Apache License 2.0 |
src/year2022/11/Day11.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`11`
import java.math.BigInteger
import readInput
fun main() {
fun runRound(monkeys: List<Monkey>, is3: Boolean) {
val divider = monkeys.fold(1L) { item, monkey -> item * monkey.divisibleBy }
monkeys.forEach { monkey ->
monkey.startingItems.forEach { item ->
val newWorryLevel = (monkey.operation(item) / if (is3) 3L else 1L) % divider
monkey.inspectedCount++
val newMonkey = if (newWorryLevel % monkey.divisibleBy == 0L) {
monkey.trueDest
} else {
monkey.falseDest
}
monkeys[newMonkey].startingItems.add(newWorryLevel)
}
monkey.startingItems.clear()
}
}
fun part1(input: List<String>): BigInteger {
val data = parseInput(input)
repeat(20) { runRound(data, true) }
val (firstMonkey, secondMonkey) = data.sortedByDescending { it.inspectedCount }
return firstMonkey.inspectedCount * secondMonkey.inspectedCount
}
fun part2(input: List<String>): BigInteger {
val data = parseInput(input)
repeat(10000) { runRound(data, false) }
val (firstMonkey, secondMonkey) = data.sortedByDescending { it.inspectedCount }
return firstMonkey.inspectedCount * secondMonkey.inspectedCount
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 10605.toBigInteger())
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
data class Monkey(
val index: Int,
val startingItems: MutableList<Long>,
val operation: (Long) -> Long,
val divisibleBy: Long,
val trueDest: Int,
val falseDest: Int,
var inspectedCount: BigInteger = 0.toBigInteger()
)
fun parseInput(input: List<String>): List<Monkey> {
return input.chunked(7)
.map {
val monkeyIndex = it[0]
.replace("Monkey", "")
.trim()
.dropLast(1)
.toInt()
val startingItems = it[1]
.replace("Starting items:", "")
.trim()
.split(",")
.map { it.trim().toLong() }
val operation = it[2]
.replace("Operation: new =", "")
.trim()
.split(" ")
val lambda: (Long) -> Long = { firstNumber ->
val (_, op, third) = operation
val secondNumber = third.takeIf { it != "old" }?.toLong() ?: firstNumber
when (op) {
"*" -> firstNumber * secondNumber
"+" -> firstNumber + secondNumber
else -> error("!!")
}
}
val divisibleBy = it[3].replace("Test: divisible by", "").trim().toLong()
val ifTrue = it[4].replace("If true: throw to monkey", "").trim().toInt()
val ifFalse = it[5].replace("If false: throw to monkey", "").trim().toInt()
Monkey(
index = monkeyIndex,
startingItems = startingItems.toMutableList(),
operation = lambda,
divisibleBy = divisibleBy,
trueDest = ifTrue,
falseDest = ifFalse
)
}
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 3,467 | KotlinAdventOfCode | Apache License 2.0 |
src/day_12/Day12.kt | BrumelisMartins | 572,847,918 | false | {"Kotlin": 32376} | package day_12
import day_03.alphabet
import readInput
import java.util.*
import kotlin.collections.ArrayList
fun main() {
val input = readInput("day_12/Day12")
val testInput = fromRawData(readInput("day_12/Day12_test"))
fun part1(): Int {
val finder = PathFinder(fromRawData(input))
finder.run()
val shortest = finder.findShortestPath()
val newlist = finder.sourceDataGrid.map { if (shortest.contains(it)) it.value else "." }
.chunked(input.first().length)
newlist.forEach {
it.forEach { string ->
print(string)
}
println()
}
println(shortest.size)
return 0
}
println(part1())
}
fun fromRawData(rawData: List<String>): List<Node> {
val data = rawData.map { it.toList() }
.mapIndexed { row, list ->
list.mapIndexed { index, s ->
val indexSize = if (row == 0) 0 else list.size * row
Node(index + indexSize, s.toString())
}
}
val listOfNodes = mutableListOf<Node>()
(data.indices).flatMap { row ->
(data[row].indices).map { column ->
val current = data[row][column]
current.addAdjacentNode(data.getOrNull(row - 1)
?.getOrNull(column))
current.addAdjacentNode(data.getOrNull(row + 1)
?.getOrNull(column))
current.addAdjacentNode(data.getOrNull(row)
?.getOrNull(column - 1))
current.addAdjacentNode(data.getOrNull(row)
?.getOrNull(column + 1))
listOfNodes.add(current)
}
}
return listOfNodes
}
fun isAdjacent(current: Node, childNode: Node?): Boolean {
if (childNode == null) return false
val height = alphabet.indexOf(current.value.mapToElevation())
val childHeight = alphabet.indexOf(childNode.value.mapToElevation())
return (childHeight - height) <= 1
}
fun String.mapToElevation(): String {
if (equals("S")) return "a"
return if (equals("E")) "z"
else this
}
data class Node(val index: Int, val value: String, val adjacentNodes: ArrayList<Node> = arrayListOf()) {
fun addAdjacentNode(childNode: Node?) {
if (isAdjacent(this, childNode)) adjacentNodes.add(childNode!!)
}
}
class PathFinder(val sourceDataGrid: List<Node>) {
private val nodeCount = sourceDataGrid.size // number of nodes
private val source = sourceDataGrid.first()
private val destination = sourceDataGrid.first { it.value == "E" }
private var queue = ArrayDeque<Node>()
private var visited = mutableListOf(source)
val lengths = IntArray(nodeCount)
private val parents = sourceDataGrid.toMutableList()
fun run() {
queue.push(source)
while (!queue.isEmpty()) {
val current = queue.pop()
current.adjacentNodes.forEach {
if (!visited.contains(it)) {
visited.add(it)
queue.addLast(it)
lengths[it.index] = lengths[current.index] + 1
parents[it.index] = current
}
}
}
}
fun findShortestPath(): List<Node> {
return if (!visited.contains(destination)) {
listOf()
} else {
val path = arrayListOf(destination)
var v: Node = destination
while (v.index != 0) {
path.add(parents[v.index])
v = parents[v.index]
}
path.reversed()
}
}
}
| 0 | Kotlin | 0 | 0 | 3391b6df8f61d72272f07b89819c5b1c21d7806f | 3,591 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | hoppjan | 573,053,610 | false | {"Kotlin": 9256} | import RPS.*
import Tactic.*
fun main() {
val testLines = readInput("Day02_test")
val testResult1 = part1(testLines)
println("test part 1: $testResult1")
check(testResult1 == 15)
val testResult2 = part2(testLines)
println("test part 2: $testResult2")
check(testResult2 == 12)
val lines = readInput("Day02")
println("part 1: ${part1(lines)}")
println("part 2: ${part2(lines)}")
}
private fun part1(input: List<String>) = parseRockPaperScissors(input)
.sumOf { match -> match.myScore() }
private fun part2(input: List<String>): Int = parseRockPaperScissors(input)
.sumOf { match -> match.copy(myHand = match.tacticalMe()).myScore() }
private fun Match.tacticalMe() =
when (tactic) {
Win -> beat(opponent)
Tie -> opponent
Loss -> giveInAgainst(opponent)
}
private fun beat(opponent: RPS) = when (opponent) {
Rock -> Paper
Paper -> Scissors
Scissors -> Rock
}
private fun giveInAgainst(opponent: RPS) = when (opponent) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
private fun parseRockPaperScissors(input: List<String>) =
input.map { line ->
line.split(" ").let { (first, second) -> Match(first, second) }
}
private enum class RPS {
Rock, Paper, Scissors;
val score = ordinal + 1
}
private enum class Tactic {
Loss, Tie, Win;
val score = ordinal * 3
}
private fun Match.myScore(): Int = myHand.score + winningScore()
private data class Match(val opponent: RPS, val myHand: RPS) {
constructor(opponent: String, me: String): this(opponent.toRPS(), me.toRPS())
val tactic = myHand.toTactic()
}
private fun String.toRPS() = when (this) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> throw Exception("Do you even understand what we are playing?")
}
private fun RPS.toTactic() = when (this) {
Rock -> Loss
Paper -> Tie
Scissors -> Win
}
private fun Match.winningScore(): Int =
when (opponent) {
myHand -> Tie
Rock -> myHand.winsWith(Paper)
Paper -> myHand.winsWith(Scissors)
Scissors -> myHand.winsWith(Rock)
}.score
private fun RPS.winsWith(value: RPS) = if (this == value) Win else Loss
| 0 | Kotlin | 0 | 0 | f83564f50ced1658b811139498d7d64ae8a44f7e | 2,237 | advent-of-code-2022 | Apache License 2.0 |
src/day08/day08.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day08
import util.Grid
import util.readInput
import util.shouldBe
import util.toGrid
fun main() {
val day = 8
val testInput = readInput(day, testInput = true).parseInput()
part1(testInput) shouldBe 21
part2(testInput) shouldBe 8
val input = readInput(day).parseInput()
println("output for part1: ${part1(input)}")
println("output for part2: ${part2(input)}")
}
private class Tree(
val height: Int,
var isVisible: Boolean = false,
var visibilityScore: Int = 1,
)
private class Input(
val grid: Grid<Tree>,
)
private fun List<String>.parseInput(): Input {
return Input(toGrid { _, _, it -> Tree(it.digitToInt()) })
}
private fun computeVisibility(trees: List<Tree>) {
var maxHeight = -1
for (tree in trees) {
if (tree.height > maxHeight) {
maxHeight = tree.height
tree.isVisible = true
}
}
}
private fun part1(input: Input): Int {
for (column in input.grid.columns()) {
computeVisibility(column)
computeVisibility(column.asReversed())
}
for (row in input.grid.rows()) {
computeVisibility(row)
computeVisibility(row.asReversed())
}
return input.grid.values().count { it.isVisible }
}
private fun computeVisibilityScore(trees: List<Tree>) {
val distances = IntArray(10)
for (tree in trees) {
tree.visibilityScore *= distances[tree.height]
for (i in 0..9) distances[i] = if (tree.height >= i) 1 else distances[i] + 1
}
}
private fun part2(input: Input): Int {
for (column in input.grid.columns()) {
computeVisibilityScore(column)
computeVisibilityScore(column.asReversed())
}
for (row in input.grid.rows()) {
computeVisibilityScore(row)
computeVisibilityScore(row.asReversed())
}
return input.grid.values().maxOf { it.visibilityScore }
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 1,883 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/kr/co/programmers/P72411.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/386
class P72411 {
fun solution(orders: Array<String>, course: IntArray): Array<String> {
val answer = mutableListOf<String>()
// 메뉴조합을 오름차순으로 정렬
val sorted = orders.map { it.toCharArray().sorted() }
// 메뉴별 갯수별 가능한 모든 조합을 구한다.
val combination = mutableListOf<String>()
for (chars in sorted) {
for (c in course) {
combination(combination, chars, BooleanArray(chars.size), 0, c)
}
}
// 문자열의 길이별로 그룹핑
val count = combination.groupBy { it.length }
for (e in count) {
// 문자열별 횟수로 그룹핑
val g = e.value.groupingBy { it }.eachCount()
// 2회 이상 주문되고 가장 많이 주문된 횟수를 구한다.
var max = Int.MIN_VALUE
for (v in g.values) {
if (v >= 2 && v > max) max = v
}
// 최대 주문수가 있다면 주문된 조합을 찾는다.
if (max != Int.MIN_VALUE) {
g.filter { it.value == max }.forEach { (t, _) -> answer += t }
}
}
// 최종 메뉴 조합도 오름차순으로 정렬해서 리턴
return answer.sorted().toTypedArray()
}
private fun combination(result: MutableList<String>, arr: List<Char>, visited: BooleanArray, index: Int, r: Int) {
if (r == 0) {
result += arr.filterIndexed { i, _ -> visited[i] }.joinToString("")
} else if (index == arr.size) {
return
} else {
visited[index] = true // 선택하는 경우
combination(result, arr, visited, index + 1, r - 1)
visited[index] = false // 선택하지 않는 경우
combination(result, arr, visited, index + 1, r)
}
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,976 | algorithm | MIT License |
src/day07/Day07.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day07
import utils.*
open class Entity(open val size: Int = 0)
class File(size: Int) : Entity(size)
class Directory(val parent: Directory? = null) : Entity() {
val contents: MutableMap<String, Entity> = mutableMapOf()
private var _size: Int? = null
override val size: Int get() = _size
?: contents.values
.sumOf { it.size }
.also { _size = it }
val subDirs: Sequence<Directory> get() = sequence {
yield(this@Directory)
contents.values
.filterIsInstance<Directory>()
.forEach { yieldAll(it.subDirs) }
}
}
fun readCommands(lines: List<String>): Directory {
val root = Directory()
var dir = root
lines.forEach { line ->
val parts = line.split(" ")
if (parts[0] == "$" && parts[1] == "cd") {
dir = when (parts[2]) {
"/" -> root
".." -> dir.parent!!
else -> dir.contents[parts[2]]!! as Directory
}
}
if (parts[0] != "$") {
val name = parts[1]
if (name !in dir.contents)
dir.contents[name] = if (parts[0] == "dir")
Directory(dir)
else
File(parts[0].toInt())
}
}
return root
}
fun part1(input: List<String>, maxSize: Int = 100000): Int =
readCommands(input).subDirs
.filter { it.size <= maxSize }
.sumOf { it.size }
fun part2(input: List<String>, neededSpace: Int = 40000000): Int {
val root = readCommands(input)
val target = maxOf(0, root.size - neededSpace)
return root.subDirs
.filter { it.size >= target }
.minOf { it.size }
}
fun main() {
val testInput = readInput("Day07_test")
expect(part1(testInput), 95437)
expect(part2(testInput), 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 1,941 | AOC-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/de/pgebert/aoc/days/Day07.kt | pgebert | 724,032,034 | false | {"Kotlin": 65831} | package de.pgebert.aoc.days
import de.pgebert.aoc.Day
class Day07(input: String? = null) : Day(7, "Camel Cards ", input) {
private val positionsWithoutJoker = listOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A')
private val positionsWithJoker = listOf('J', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A')
override fun partOne() = inputList
.map { it.parse() }
.sortedWith(
compareBy<Pair<String, Int>> { it.first.getType() }
.thenComparing({ it.first }, { a, b -> a.compareHandTo(b) })
)
.mapIndexed { i, (_, bid) -> (i + 1) * bid }
.sum()
private fun String.parse() = split(" ").let { it.first() to it.last().toInt() }
private fun String.getType(): Int {
val counts = groupingBy { it }.eachCount().values.sortedDescending()
val first = counts.getOrElse(0) { 0 }
val second = counts.getOrElse(1) { 0 }
return when {
first == 5 -> 6 // Five of a kind
first == 4 -> 5 // Four of a kind
first == 3 && second == 2 -> 4 // Full house
first == 3 -> 3 // Three of a kind
first == 2 && second == 2 -> 2 // Two pair
first == 2 -> 1 // One pair
else -> 0 // High card
}
}
private fun String.compareHandTo(other: String): Int {
if (isEmpty()) 0
val thisValue = positionsWithoutJoker.indexOf(first())
val otherValue = positionsWithoutJoker.indexOf(other.first())
return thisValue.compareTo(otherValue).takeIf { it != 0 } ?: drop(1).compareHandTo(other.drop(1))
}
override fun partTwo() = inputList.map {
it.parse()
}
.sortedWith(
compareBy<Pair<String, Int>> { it.first.getTypeWithJoker() }.thenComparing(
{ it.first },
{ a, b ->
a.compareHandWithJokerTo(b)
}
)
)
.mapIndexed { index, (_, bid) -> (index + 1) * bid }.sum()
private fun String.compareHandWithJokerTo(other: String): Int {
if (isEmpty()) 0
val thisValue = positionsWithJoker.indexOf(first())
val otherValue = positionsWithJoker.indexOf(other.first())
return thisValue.compareTo(otherValue).takeIf { it != 0 } ?: drop(1).compareHandWithJokerTo(other.drop(1))
}
private fun String.getTypeWithJoker(): Int {
val counts = groupingBy { it }.eachCount()
val first = counts.filterKeys { it != 'J' }.values.sortedDescending().getOrElse(0) { 0 }
val second = counts.filterKeys { it != 'J' }.values.sortedDescending().getOrElse(1) { 0 }
val joker = counts.getOrDefault('J', 0)
return when {
first + joker == 5 -> 6 // Five of a kind
first + joker == 4 -> 5 // Four of a kind
first + joker == 3 && second == 2 -> 4 // Full house
first + joker == 3 -> 3 // Three of a kind
first == 2 && second + joker == 2 -> 2 // Two pair
first + joker == 2 -> 1 // One pair
else -> 0 // High card
}
}
}
| 0 | Kotlin | 1 | 0 | a30d3987f1976889b8d143f0843bbf95ff51bad2 | 3,151 | advent-of-code-2023 | MIT License |
Advent-of-Code-2023/src/Day06.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day06"
private const val PART1_TEST_FILE = "${AOC_DAY}_test_part1"
private const val PART2_TEST_FILE = "${AOC_DAY}_test_part2"
private const val INPUT_FILE = AOC_DAY
/**
* Finds the minimum time required to go further than the record distance, and then, since the results are symmetric,
* we can also get the maximum time required. Then, we store the count of numbers between the min and max.
* @return the product of the possibilities for each time of getting further than the record distance.
*/
private fun part1(input: List<String>): Int {
val parsedInput = parseInput(input)
val times = parsedInput.first.map { it.toInt() }
val distances = parsedInput.second.map { it.toInt() }
val waysToWin = mutableListOf<Int>()
for ((time, distance) in times.zip(distances)) {
for (j in 1..<time / 2) {
if (j * (time - j) <= distance) continue
waysToWin.add(time - j - j + 1)
break
}
}
return waysToWin.reduce(Int::times)
}
/**
* The same objective as in part1, however here we only have one time and a corresponding record distance, since the
* numbers in the sheet of paper are supposed to be interpreted as a single number.
* @return the number of possibilities of getting further than the record distance.
*/
private fun part2(input: List<String>): Long {
val (times, distances) = parseInput(input)
val time = times.joinToString("").toLong()
val distance = distances.joinToString("").toLong()
for (j in 1..<time / 2) {
if (j * (time - j) <= distance) continue
return time - j - j + 1
}
return 0
}
typealias Times = List<String>
typealias Distances = List<String>
private fun parseInput(input: List<String>): Pair<Times, Distances> {
val spacesRegex = Regex("\\s+")
val times = input.first().removePrefix("Time:").trim().split(spacesRegex)
val distances = input.last().removePrefix("Distance:").trim().split(spacesRegex)
return Pair(times, distances)
}
fun main() {
val part1ExpectedRes = 288
val part1TestInput = readInputToList(PART1_TEST_FILE)
println("---| TEST INPUT |---")
println("* PART 1: ${part1(part1TestInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 71503
val part2TestInput = readInputToList(PART2_TEST_FILE)
println("* PART 2: ${part2(part2TestInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 393120" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 36872656" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 2,681 | Advent-of-Code-2023 | Apache License 2.0 |
src/day11/Day11.kt | Regiva | 573,089,637 | false | {"Kotlin": 29453} | package day11
import readText
import kotlin.math.pow
fun main() {
val id = "11"
val testOutput = 10605
val testInput = readInput("day$id/Day${id}_test_simple")
println(part1(testInput))
check(part1(testInput) == testOutput.toLong())
val input = readInput("day$id/Day${id}_simple")
println(part1(input))
println(part2(input))
}
typealias Worry = Long
class Monkey(
val items: MutableList<Worry>,
private val operation: (Worry) -> Worry,
val assertValue: Int,
private val ifTrueMonkey: Int,
private val ifFalseMonkey: Int,
) {
var activity = 0L
private set
private val initialItems = items.toList()
fun inspectItems(decreaseFactor: Int = 1): List<Transition> {
val transitions = mutableListOf<Transition>()
for (worry in items) {
val changedWorry = operation(worry) / decreaseFactor
transitions += throwItem(changedWorry, test(changedWorry))
activity++
}
items.clear()
return transitions
}
private fun throwItem(worry: Worry, monkeyId: Int): Transition {
return Transition(worry, monkeyId)
}
private fun test(worry: Worry) = if (worry % assertValue == 0L) ifTrueMonkey else ifFalseMonkey
fun reset() {
activity = 0
items.clear()
items.addAll(initialItems)
}
}
data class Transition(
val worry: Worry,
val monkeyId: Int,
)
fun readInput(fileName: String): List<Monkey> {
return readText(fileName).split("\n\n")
.map { text ->
val (items, operation, assert, ifTrueMonkey, ifFalseMonkey) = text.split("\n")
Monkey(
items = ArrayDeque(items.split(" ").map { it.toLong() }),
operation = { worry ->
val (operator, value) = operation.split(" ")
when (operator) {
"+" -> worry + value.toInt()
"*" -> worry * value.toInt()
"^" -> worry.toDouble().pow(value.toInt()).toLong()
else -> worry
}
},
assertValue = assert.toInt(),
ifTrueMonkey = ifTrueMonkey.toInt(),
ifFalseMonkey = ifFalseMonkey.toInt(),
)
}
}
fun part1(monkeys: List<Monkey>): Long {
for (monkey in monkeys) monkey.reset()
for (round in 1..20) {
for (monkey in monkeys) {
for (transition in monkey.inspectItems(decreaseFactor = 3)) {
val (item, id) = transition
monkeys[id].items.add(item)
}
}
}
return monkeys.map { it.activity }.sortedDescending().take(2).reduce(Long::times)
}
fun part2(monkeys: List<Monkey>): Long {
val mod = monkeys.map { it.assertValue }.reduce(Int::times)
for (monkey in monkeys) monkey.reset()
for (round in 1..10000) {
for (monkey in monkeys) {
for (transition in monkey.inspectItems()) {
val (item, id) = transition
monkeys[id].items.add(item % mod)
}
}
}
return monkeys.map { it.activity }.sortedDescending().take(2).reduce(Long::times)
}
| 0 | Kotlin | 0 | 0 | 2d9de95ee18916327f28a3565e68999c061ba810 | 3,242 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/kotlin/codes/jakob/aoc/solution/Day02.kt | loehnertz | 725,944,961 | false | {"Kotlin": 59236} | package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.associateByIndex
import codes.jakob.aoc.shared.multiply
import codes.jakob.aoc.shared.splitByLines
object Day02 : Solution() {
override fun solvePart1(input: String): Any {
// The amount of cubes of each type is constrained by the following rules:
val cubeAmountConstraints: Map<CubeType, Int> = mapOf(
CubeType.RED to 12,
CubeType.GREEN to 13,
CubeType.BLUE to 14,
)
// The games are represented as a map of game index to a list of reveals.
val games: Map<Int, List<Map<CubeType, Int>>> = parseGames(input)
// We filter out all games that violate the cube amount constraints.
val possibleGames: Map<Int, List<Map<CubeType, Int>>> = games
.filterValues { game: List<Map<CubeType, Int>> ->
val maximumSeenCubes: Map<CubeType, Int> = countMaximumCubeAmount(game)
maximumSeenCubes.all { (cubeType: CubeType, maximumSeen: Int) ->
maximumSeen <= cubeAmountConstraints.getOrDefault(cubeType, 0)
}
}
// We sum up the game indices of the possible games.
return possibleGames.keys.sum()
}
override fun solvePart2(input: String): Any {
// The games are represented as a map of game index to a list of reveals.
val games: Map<Int, List<Map<CubeType, Int>>> = parseGames(input)
// We calculate the minimum required cubes per game.
val minimumRequiredCubesPerGame: Map<Int, Map<CubeType, Int>> = games
.mapValues { (_, game: List<Map<CubeType, Int>>) -> countMaximumCubeAmount(game).toMap() }
// We sum up the minimum required cubes per game.
return minimumRequiredCubesPerGame
.map { (_, minimumRequiredCubes: Map<CubeType, Int>) -> minimumRequiredCubes.values.multiply() }
.sum()
}
/**
* Parses the input into a map of game index to a list of reveals.
*/
private fun parseGames(input: String): Map<Int, List<Map<CubeType, Int>>> {
/**
* Parses a single game.
* A game is represented as a list of reveals. A reveal is represented as a map of cube type to amount.
* Example: "red 1, green 2, blue 3" -> {RED=1, GREEN=2, BLUE=3}
*/
fun parseGame(line: String): List<Map<CubeType, Int>> {
/**
* Parses a single reveal.
* A reveal is represented as a map of cube type to amount.
*/
fun parseCubeAmount(cubeString: String): Pair<CubeType, Int> {
val (amount, type) = cubeString.split(" ")
return CubeType.fromSign(type) to amount.toInt()
}
// We split the line into reveals, then we split each reveal into cube types and amounts.
return line
.substringAfter(": ")
.split("; ")
.map { reveal -> reveal.split(", ") }
.map { reveal -> reveal.map { parseCubeAmount(it) } }
.map { reveal -> reveal.toMap() }
}
// We split the input into games, then we parse each game.
// We then associate each game with its index (as it's given with its index in the input).
return input
.splitByLines()
.map { parseGame(it) }
.associateByIndex()
.mapKeys { (index, _) -> index + 1 }
}
/**
* Counts the maximum amount of cubes of each type that are seen in a game.
*/
private fun countMaximumCubeAmount(game: List<Map<CubeType, Int>>): Map<CubeType, Int> {
val maximumSeenCubes: MutableMap<CubeType, Int> = mutableMapOf()
game.forEach { reveal: Map<CubeType, Int> ->
reveal.forEach { (cubeType: CubeType, amount: Int) ->
maximumSeenCubes[cubeType] = maxOf(maximumSeenCubes.getOrDefault(cubeType, 0), amount)
}
}
return maximumSeenCubes
}
/**
* Represents the type of cube.
* The type of cube is represented as a sign (e.g., "red", "green", "blue").
*/
enum class CubeType {
RED,
GREEN,
BLUE;
companion object {
fun fromSign(sign: String): CubeType {
return when (sign) {
"red" -> RED
"green" -> GREEN
"blue" -> BLUE
else -> error("Unknown cube type: $sign")
}
}
}
}
}
fun main() {
Day02.solve()
}
| 0 | Kotlin | 0 | 0 | 6f2bd7bdfc9719fda6432dd172bc53dce049730a | 4,604 | advent-of-code-2023 | MIT License |
src/Day08.kt | robotfooder | 573,164,789 | false | {"Kotlin": 25811} | data class Grid(val cells: List<Cell>) {
fun getLeftNeighbors(cell: Cell): List<Cell> {
return cells.filter { it.row == cell.row && it.col < cell.col }
}
fun getRightNeighbors(cell: Cell): List<Cell> {
return cells.filter { it.row == cell.row && it.col > cell.col }
}
fun getTopNeighbors(cell: Cell): List<Cell> {
return cells.filter { it.col == cell.col && it.row < cell.row }
}
fun getBottomNeighbors(cell: Cell): List<Cell> {
return cells.filter { it.col == cell.col && it.row > cell.row }
}
}
data class Cell(val row: Int, val col: Int, val value: Int = 0)
fun main() {
fun buildGrid(input: List<String>): Grid {
return Grid(input
.flatMapIndexed { rowIndex, row ->
row.toList()
.mapIndexed { colIndex, value -> Cell(rowIndex, colIndex, value.digitToInt()) }
})
}
fun part1(input: List<String>): Int {
val grid = buildGrid(input)
val rows = input.count()
val columns = input[0].toList().count()
val edges = rows + rows + columns + columns - 4
val visible = grid.cells
.filter { it.col != 0 && it.row != 0 && it.col != columns - 1 && it.row != rows - 1 }
.filter {
with(grid) {
getLeftNeighbors(it).all { neighbor -> neighbor.value < it.value }
.or(getRightNeighbors(it).all { neighbor -> neighbor.value < it.value })
.or(getBottomNeighbors(it).all { neighbor -> neighbor.value < it.value })
.or(getTopNeighbors(it).all { neighbor -> neighbor.value < it.value })
}
}
return edges + visible.size
}
fun score(cellValue: Int, neighbors: List<Cell>): Int {
val smaller = neighbors.takeWhile { it.value < cellValue }
return if (neighbors.size > smaller.size) {
smaller.size + 1
} else {
smaller.size
}
}
fun score(cell: Cell, grid: Grid): Int {
val left = score(cell.value, grid.getLeftNeighbors(cell).reversed())
val right = score(cell.value, grid.getRightNeighbors(cell))
val top = score(cell.value, grid.getTopNeighbors(cell).reversed())
val bottom = score(cell.value, grid.getBottomNeighbors(cell))
return left * right * top * bottom
}
fun part2(input: List<String>): Int {
val grid = buildGrid(input)
return grid.cells.maxOfOrNull { score(it, grid) }!!
}
val day = "08"
// test if implementation meets criteria from the description, like:
runTest(21, day, ::part1)
runTest(8, day, ::part2)
val input = readInput(day)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 9876a52ef9288353d64685f294a899a58b2de9b5 | 2,809 | aoc2022 | Apache License 2.0 |
src/main/kotlin/aoc2021/Day13.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
import kotlin.math.max
private fun Boolean.toInt() = if (this) 1 else 0
/**
* Folds the transparent input page according to the given instructions
*
* @param array the page to aoc2021.fold
* @param foldInstruction folding instruction in the form of 'aoc2021.fold along x=42'
* @return the folded transparent page with all the points marked on each side of the folding line overlayed with each other
*/
private fun fold(array: Array<BooleanArray>, foldInstruction: String): Array<BooleanArray> {
val split = foldInstruction.removePrefix("aoc2021.fold along ").split("=")
val foldAxis = split[0]
val foldValue = split[1].toInt()
val result = if (foldAxis == "y") {
Array(array.size) { BooleanArray(foldValue + 1) }
} else {
Array(foldValue + 1) { BooleanArray(array.firstOrNull()?.size ?: 0) }
}
for (x in array.indices) {
for (y in 0 until (array.firstOrNull()?.size ?: 0)) {
if ((foldAxis == "x" && x <= foldValue) or (foldAxis == "y" && y <= foldValue)) {
result[x][y] = array[x][y]
} else if (foldAxis == "x") {
val newX = max(0, 2 * foldValue - x)
result[newX][y] = result[newX][y] or array[x][y]
} else {
val newY = max(0, 2 * foldValue - y)
result[x][newY] = result[x][newY] or array[x][y]
}
}
}
return result
}
/**
* Parses the input string of the initial points into a 2D array
*/
private fun parseArray(input: List<String>): Array<BooleanArray> {
val maxX = input.maxOf { it.split(",")[0].toInt() }
val maxY = input.maxOf { it.split(",")[1].toInt() }
val result = Array(maxX + 1) { BooleanArray(maxY + 1) }
input.map { line -> line.split(",").map { it.toInt() } }.forEach { result[it[0]][it[1]] = true }
return result
}
private fun part1(input: List<String>): Int {
val initial = parseArray(input.takeWhile { it.isNotEmpty() })
val instruction = input.dropWhile { it.isNotBlank() }.drop(1).first()
return fold(initial, instruction).sumOf { x ->
x.sumOf { y -> y.toInt() }
}
}
private fun part2(input: List<String>): String {
var current = parseArray(input.takeWhile { it.isNotEmpty() })
val instructions = input.dropWhile { it.isNotBlank() }.drop(1)
instructions.forEach { current = fold(current, it) }
return buildString {
for (y in 0 until (current.firstOrNull()?.size ?: 0)) {
for (x in current.indices) {
append(if (current[x][y]) "#" else ".")
}
appendLine()
}
}
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 17)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 2,909 | adventOfCode | Apache License 2.0 |
src/main/kotlin/days/Day12.kt | julia-kim | 569,976,303 | false | null | package days
import Point
import readInput
import kotlin.math.absoluteValue
fun main() {
fun part1(input: List<String>): Int {
/* Dijkstra's algorithm */
val heightmap = input.flatMapIndexed { i, string ->
string.mapIndexed { j, char -> Point(j, i) to char }
}.toMap().toMutableMap()
val s = heightmap.entries.find { it.value == 'S' }!!.key
val target = heightmap.entries.find { it.value == 'E' }!!.key
heightmap[s] = 'a'
heightmap[target] = 'z'
val distances = heightmap.map { it.key to Int.MAX_VALUE }.toMap().toMutableMap()
distances[s] = 0
val unvisited = distances.keys.toMutableList()
while (unvisited.isNotEmpty()) {
val current = distances.filter { unvisited.contains(it.key) }.minBy { it.value }
val neighbors =
distances.filter { ((it.key.x - current.key.x).absoluteValue == 1 && it.key.y == current.key.y) || ((it.key.y - current.key.y).absoluteValue == 1 && it.key.x == current.key.x) }
.filter {
val currentElevation = heightmap[current.key]!!
val neighborElevation = heightmap[it.key]!!
neighborElevation <= currentElevation + 1
}
.toMutableMap()
neighbors.remove(current.key)
neighbors.forEach { neighbor ->
if (distances[neighbor.key]!! > distances[current.key]!! + 1) {
distances[neighbor.key] = distances[current.key]!! + 1
}
}
if (current.key == target) {
return distances[target]!!
}
unvisited.remove(current.key)
}
return 0
}
fun part2(input: List<String>): Int {
/* Dijkstra's algorithm */
val heightmap = input.flatMapIndexed { i, string ->
string.mapIndexed { j, char -> Point(j, i) to char }
}.toMap().toMutableMap()
val s = heightmap.entries.find { it.value == 'S' }!!.key
val start = heightmap.entries.find { it.value == 'E' }!!.key
heightmap[s] = 'a'
heightmap[start] = 'z'
val target = heightmap.entries.filter { it.value == 'a' }.map { it.key }
val distances = heightmap.map { it.key to Int.MAX_VALUE }.toMap().toMutableMap()
distances[start] = 0
val unvisited = distances.keys.toMutableList()
while (unvisited.isNotEmpty()) {
val current = distances.filter { unvisited.contains(it.key) }.minBy { it.value }
val neighbors =
distances.filter { ((it.key.x - current.key.x).absoluteValue == 1 && it.key.y == current.key.y) || ((it.key.y - current.key.y).absoluteValue == 1 && it.key.x == current.key.x) }
.filter {
val currentElevation = heightmap[current.key]!!
val neighborElevation = heightmap[it.key]!!
neighborElevation - currentElevation >= -1
}
.toMutableMap()
neighbors.remove(current.key)
neighbors.forEach { neighbor ->
if (distances[neighbor.key]!! > distances[current.key]!! + 1) {
distances[neighbor.key] = distances[current.key]!! + 1
}
}
if (target.contains(current.key)) {
return distances[current.key]!!
}
unvisited.remove(current.key)
}
println(distances.filter { target.contains(it.key) })
return distances.filter { target.contains(it.key) }.values.min()
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 3,896 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day3.kt | i-redbyte | 433,743,675 | false | {"Kotlin": 49932} | fun main() {
fun part2(lines: List<String>): Int {
val oxygen = lines.toMutableList()
val scrubber = lines.toMutableList()
for (i in 0 until lines.first().length) {
val ox = oxygen.groupingBy { it[i] }
.eachCount()
.entries
.maxWithOrNull(compareBy({ it.value }, { it.key }))!!.key
val scrub = scrubber.groupingBy { it[i] }
.eachCount()
.entries
.minWithOrNull(compareBy({ it.value }, { it.key }))!!.key
oxygen.retainAll { it[i] == ox }
scrubber.retainAll { it[i] == scrub }
}
println("oxygen = ${oxygen.single().toInt(2)} scrubber = ${scrubber.single().toInt(2)}")
return oxygen.single().toInt(2) * scrubber.single().toInt(2)
}
fun part1() {
val dataMatrix: List<List<Int>> = readInputFile("day3")
.map { it.toList() }
.map { it.map { it.digitToInt() } }
val n = dataMatrix.size
val m = dataMatrix[0].size
val h: Int = n / 2
val map =
mutableMapOf(
Pair(0, 0), Pair(1, 0), Pair(2, 0), Pair(3, 0), Pair(4, 0), Pair(5, 0), Pair(6, 0),
Pair(7, 0), Pair(8, 0), Pair(9, 0), Pair(10, 0), Pair(11, 0)
)
for (i in 0 until n) {
for (j in 0 until m) {
if (dataMatrix[i][j] == 1) {
map[j] = map[j]!! + 1
}
}
}
var epsilon = ""
var gamma = ""
for ((_, v) in map) {
if (v >= h) {
gamma += "1"
epsilon += "0"
} else {
gamma += "0"
epsilon += "1"
}
}
println("gamma =${gamma.toInt(2)} epsilon =${epsilon.toInt(2)}")
println("Result = ${gamma.toInt(2) * epsilon.toInt(2)}")
}
part1()
println("Result part 2: ${part2(readInputFile("day3"))}")
}
| 0 | Kotlin | 0 | 0 | 6d4f19df3b7cb1906052b80a4058fa394a12740f | 2,008 | AOC2021 | Apache License 2.0 |
src/main/kotlin/be/swsb/aoc2021/day9/Day9.kt | Sch3lp | 433,542,959 | false | {"Kotlin": 90751} | package be.swsb.aoc2021.day9
import be.swsb.aoc2021.common.Point
import java.util.*
object Day9 {
fun solve1(input: List<String>): Int {
val heightmap = input.toHeightmap()
return heightmap.findLowest().sumOf { it.riskLevel }
}
fun solve2(input: List<String>): Int {
val heightmap = input.toHeightmap()
val allBasins = heightmap.findBasins()
checkNoMergingBasins(allBasins)
val threeLargestBasins = allBasins
.sortedByDescending { it.size }
.take(3)
return threeLargestBasins.map { it.size }.reduce { prev, cur -> prev * cur }
}
private fun checkNoMergingBasins(allBasins: List<Basin>) {
val mergingBasins = allBasins.map { basin ->
(allBasins - basin).filter { otherBasin -> basin.containsAnyOf(otherBasin) }
}.filterNot { it.isEmpty() }
if (mergingBasins.isNotEmpty()) {
throw IllegalStateException(mergingBasins.joinToString("\n") { "These basins are merging: $it" })
}
}
}
fun List<String>.toHeightmap() = HeightMap(
this.flatMapIndexed { idx, line ->
line.mapIndexed { lineIndex, char -> CaveTile(Point.at(lineIndex, idx), "$char".toInt()) }
}
)
data class HeightMap(val tiles: List<CaveTile>) {
private val _no9s
get() = tiles.filterNot { it.height == 9 }
private val locations by lazy { _no9s.associateBy { it.point } }
fun tilesAt(points: List<Point>): List<CaveTile> =
tilesAtUsingMap(points)
// 38.618 without lazy locations
// 0.328 with lazy locations
fun tilesAtUsingMap(points: List<Point>): List<CaveTile> =
points.mapNotNull { point -> locations[point] }
// 14.221 without lazy locations
// 3.594 with lazy locations
fun tilesAtUsingList(points: List<Point>): List<CaveTile> =
locations.filter { (point,_) -> point in points }.values.toList()
fun findLowest() =
_no9s.filter { it.isLowest(this) }
fun findBasins(): List<Basin> {
val basinBottoms = findLowest()
return basinBottoms.map { basinBottom ->
val basin = accumulateBasin(setOf(basinBottom))
Basin(tiles = basin)
}
}
private fun accumulateBasin(basin: Set<CaveTile>): Set<CaveTile> {
val possibleNextBasinPoints = basin.flatMap { basinPoint ->
basinPoint.neighbors(this).filter { it.height > basinPoint.height }
} - basin
return if (possibleNextBasinPoints.isEmpty()) {
basin
} else {
accumulateBasin(basin + possibleNextBasinPoints)
}
}
}
data class CaveTile(val point: Point, val height: Height) {
val riskLevel
get() = 1 + height
fun isLowest(heightMap: HeightMap): Boolean =
neighbors(heightMap).all { neighbour -> neighbour.height > height }
fun neighbors(heightMap: HeightMap): List<CaveTile> {
return heightMap.tilesAt(this.point.orthogonalNeighbours())
}
override fun toString() = "$point:$height"
}
class Basin(private val tiles: Set<CaveTile>, val id: UUID = UUID.randomUUID()) {
val size: Int
get() = tiles.size
val lowPoint: Point
get() = tiles.minByOrNull { it.height }!!.point
fun containsAnyOf(other: Basin): Boolean {
if (this == other) return true
if (this.tiles.isEmpty() || other.tiles.isEmpty()) return false
return this.tiles.any { tile -> tile in other.tiles }
}
override fun toString() = "Basin at $lowPoint of size $size with " + tiles.joinToString { it.toString() }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Basin) return false
return this.id == other.id
}
override fun hashCode(): Int {
return id.hashCode()
}
}
fun heightAt(x: Int, y: Int, z: Int) = CaveTile(Point.at(x, y), z)
typealias Height = Int | 0 | Kotlin | 0 | 0 | 7662b3861ca53214e3e3a77c1af7b7c049f81f44 | 3,925 | Advent-of-Code-2021 | MIT License |
src/main/day13/Part1.kt | ollehagner | 572,141,655 | false | {"Kotlin": 80353} | package day13
import dequeOf
import readInput
import java.util.*
fun main() {
val packets = parseInput(readInput("day13/input.txt"))
val indiceSum = packets
.mapIndexed { index, packet -> Pair(index + 1, validateOrder(dequeOf(packet.first), dequeOf(packet.second))) }
.filter { it.second }
.sumOf { it.first }
println("Day 13 part 1. Sum of indices: $indiceSum")
}
fun validateOrder(left: Deque<String>, right: Deque<String>): Boolean {
// left.zip(right)
// .forEach { println(it.first.padEnd(20) + it.second) }
val topLeft = left.pop().orEmpty()
val topRight = right.pop().orEmpty()
if(topLeft.isEmpty() && topRight.isEmpty()) {
return validateOrder(LinkedList(left), LinkedList(right))
}
if(topLeft.isEmpty()) {
return true
} else if(topRight.isEmpty()) {
return false
}
if(topLeft.isList() && topRight.isList()) {
if(topLeft.isEmpty() && topRight.isNotEmpty()) {
return true
} else if(topLeft.isNotEmpty() && topRight.isEmpty()) {
return false
}
val leftNextAndRemainder = nextValueAndRemainder(topLeft)
val rightNextAndRemainder = nextValueAndRemainder(topRight)
left.apply {
push(leftNextAndRemainder.second)
push(leftNextAndRemainder.first)
}
right.apply {
push(rightNextAndRemainder.second)
push(rightNextAndRemainder.first)
}
return validateOrder(LinkedList(left), LinkedList(right))
}
if(!topLeft.isList() && !topRight.isList()) {
if(topLeft.toInt() == topRight.toInt()) {
return validateOrder(LinkedList(left), LinkedList(right))
} else {
return topLeft.toInt() < topRight.toInt()
}
}
if(!topLeft.isList() && topRight.isList()) {
left.push(topLeft.toList())
right.push(topRight)
return validateOrder(LinkedList(left), LinkedList(right))
} else if(topLeft.isList() && !topRight.isList()) {
left.push(topLeft)
right.push(topRight.toList())
return validateOrder(LinkedList(left), LinkedList(right))
}
return true
}
fun parseInput(input: List<String>): List<Pair<String, String>> {
return input.windowed(2, 3)
.map { Pair(it.first(), it.last()) }
}
fun String.isList(): Boolean {
return startsWith("[") && endsWith("]")
}
fun String.toList(): String {
return "[$this]"
}
fun String.isEmpty(): Boolean {
return equals("[]")
}
fun nextValueAndRemainder(value: String): Pair<String, String> {
return value.drop(1).dropLast(1)
.fold(Pair("", "")) { acc, value ->
if(acc.second.isNotEmpty()) {
Pair(acc.first, acc.second + value)
} else if(acc.first.isNotEmpty() && (acc.first.last() == ']' || value == ',') && isBalanced(acc.first)) {
Pair(acc.first, acc.second + value)
} else {
Pair(acc.first + value, acc.second)
}
}.let { (first, second) -> Pair(first, second.drop(1).toList()) }
}
fun isBalanced(value: String): Boolean {
return value.count { it == '[' } == value.count { it == ']' }
}
| 0 | Kotlin | 0 | 0 | 6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1 | 3,232 | aoc2022 | Apache License 2.0 |
src/Day24.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | import java.util.*
fun main() {
fun start() = Vec2(0, 1)
fun List<String>.target() = Vec2(size - 1, get(0).length - 2)
data class State(val minute: Int, val pos: Vec2): Comparable<State> {
override fun compareTo(other: State): Int {
return compareValuesBy(this, other, { it.minute }, { it.pos.x }, { it.pos.y })
}
}
fun solve(table: List<String>, initial: Vec2, target: Vec2, startMinute: Int = 0): Int {
val n = table.size - 1
val m = table[0].length - 1
fun isFree(minute: Int, pos: Vec2): Boolean {
if (pos == initial) return true
fun isFreeDir(dir: Vec2, sign: Char): Boolean {
val moved = pos - Vec2(1, 1) + dir * (startMinute + minute)
val x = moved.x.mod(n - 1) + 1
val y = moved.y.mod(m - 1) + 1
return table[x][y] != sign
}
return isFreeDir(Vec2(1, 0), '^') && isFreeDir(Vec2(-1, 0), 'v') &&
isFreeDir(Vec2(0, 1), '<') && isFreeDir(Vec2(0, -1), '>')
}
val queue = PriorityQueue<State>()
val visited = mutableSetOf<State>()
val initialState = State(0, initial)
queue += initialState
visited += initialState
while (queue.isNotEmpty()) {
val cur = queue.poll()
for (dir in listOf(Vec2(0, 0), Vec2(-1, 0), Vec2(1, 0), Vec2(0, -1), Vec2(0, 1))) {
val nextPos = cur.pos + dir
if (nextPos.run { x in 0..n && y in 0..m && table[x][y] != '#'}) {
val minute = cur.minute + 1
if (nextPos == target) {
return minute
}
val nextState = State(minute, nextPos)
if (nextState !in visited) {
if (isFree(minute, nextPos)) {
queue += nextState
visited += nextState
}
}
}
}
}
return -1
}
fun part1(input: List<String>) = solve(input, start(), input.target())
fun part2(input: List<String>): Int {
val forward = solve(input, start(), input.target())
val back = solve(input, input.target(), start(), startMinute = forward)
val forward2 = solve(input, start(), input.target(), startMinute = forward + back)
return forward + back + forward2
}
val testInput = readInputLines("Day24_test")
check(part1(testInput), 18)
check(part2(testInput), 54)
val input = readInputLines("Day24")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 2,700 | Advent-of-Code-2022 | Apache License 2.0 |
y2020/src/main/kotlin/adventofcode/y2020/Day22.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2020
import adventofcode.io.AdventSolution
fun main() = Day22.solve()
object Day22 : AdventSolution(2020, 22, "Crab Combat")
{
override fun solvePartOne(input: String): Long
{
val combat = generateSequence(parse(input)) { round(it.first, it.second) }
.first { it.first.isEmpty() || it.second.isEmpty() }
val result = (combat.first + combat.second)
return result.reversed().mapIndexed { i, v -> (i + 1L) * v }.reduce(Long::plus)
}
override fun solvePartTwo(input: String): Any
{
val (a, b) = parse(input)
val combat = runGame(a, b)
val result = combat.first { it.isNotEmpty() }
return result.reversed().mapIndexed { i, v -> (i + 1L) * v }.reduce(Long::plus)
}
private fun parse(input: String): Pair<List<Int>, List<Int>>
{
val (a, b) = input.split("\n\n")
val al = a.lines().drop(1).map(String::toInt)
val bl = b.lines().drop(1).map(String::toInt)
return Pair(al, bl)
}
private fun round(a: List<Int>, b: List<Int>): Pair<List<Int>, List<Int>>
{
val (wa, wb) = a.zip(b).partition { (a, b) -> a > b }
val ra = a.drop(b.size) + wa.flatMap { listOf(it.first, it.second) }
val rb = b.drop(a.size) + wb.flatMap { listOf(it.second, it.first) }
return Pair(ra, rb)
}
private fun runGame(deckA: List<Int>, deckB: List<Int>): List<List<Int>>
{
val seen = mutableSetOf<Int>()
val d = listOf(ArrayDeque(deckA), ArrayDeque(deckB))
while (d.none { it.isEmpty() })
{
val hashCode = d.hashCode()
if (hashCode in seen) break
seen += hashCode
val tops = d.map { it.removeAt(0) }
val p1Wins = if (d[0].size >= tops[0] && d[1].size >= tops[1])
runGame(d[0].subList(0, tops[0]), d[1].subList(0, tops[1]))[0].isNotEmpty()
else
tops[0] > tops[1]
if (p1Wins) d[0].addAll(tops)
else d[1].addAll(tops.reversed())
}
return d
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,110 | advent-of-code | MIT License |
src/Day05.kt | sebastian-heeschen | 572,932,813 | false | {"Kotlin": 17461} | fun main() {
fun part1(input: List<String>): String = topOfTheStacks(input) { move, stacks ->
repeat(move.count) {
val crateToMove = stacks[move.from].removeLast()
stacks[move.to].add(crateToMove)
}
}
fun part2(input: List<String>): String = topOfTheStacks(input) { move, stacks ->
val cratesToMove = stacks[move.from].takeLast(move.count)
repeat(move.count) {
stacks[move.from].removeLast()
}
stacks[move.to].addAll(cratesToMove)
}
// 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))
}
fun topOfTheStacks(input: List<String>, operateMove: (Move, List<Stack>) -> Unit): String {
val (movements, stacks) = stacksAndMovements(input)
printStacks(stacks)
movements.forEach { move ->
println("move ${move.count} from ${move.from} to ${move.to}")
operateMove(move, stacks)
println("==================")
printStacks(stacks)
}
println("==================")
printStacks(stacks)
return stacks.mapNotNull { it.lastOrNull() }
.joinToString(separator = "")
}
fun stacksAndMovements(input: List<String>): Pair<List<Move>, List<Stack>> {
val separatorLine = input.indexOf("")
val stackCount = input[separatorLine - 1].replace(" ", "").last().digitToInt()
val stackInput = input.subList(0, separatorLine - 1)
val movements = input.subList(separatorLine + 1, input.size).map { Move.fromLine(it) }
val stacks = (0 until stackCount)
.map { stack ->
stackInput.map { line ->
val index = stack * 4 + 1
line[index]
}
}
.map {
it.reversed()
}
.map { it.filterNot { char -> char == ' ' } }
.map { it.toMutableList() }
return Pair(movements, stacks)
}
fun printStacks(stacks: List<Stack>) {
stacks.forEachIndexed { index, stack ->
println("$index: $stack")
}
}
data class Move(val count: Int, val from: Int, val to: Int) {
companion object {
fun fromLine(line: String): Move = line
.split(" ")
.mapNotNull { it.toIntOrNull() }
.run { Move(count = get(0), from = get(1) - 1, to = get(2) - 1) }
}
}
typealias Stack = MutableList<Char>
| 0 | Kotlin | 0 | 0 | 4432581c8d9c27852ac217921896d19781f98947 | 2,525 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | karloti | 573,006,513 | false | {"Kotlin": 25606} | import kotlin.math.abs
import kotlin.time.ExperimentalTime
import kotlin.time.measureTimedValue
class Day15(input: List<String>) {
private val regex = Regex("(-*\\d+)")
private val beacons = mutableSetOf<Beacon>()
private val sensors = mutableSetOf<Sensor>()
val IntRange.size get() = last.toLong() - first + 1
fun numbers(s: String) = regex.findAll(s).map { it.groupValues[1].toInt() }.toList()
fun Sensor.atLine(y1: Int) = (dist - abs(y1 - y)).takeIf { it >= 0 }?.let { IntRange(x - it, x + it) }
fun IntRange.combine(other: IntRange) =
if (first in other || last in other || other.first in this || other.last in this)
(IntRange(minOf(first, other.first), maxOf(last, other.last))) else null
data class Beacon(val x: Int, val y: Int)
data class Sensor(val x: Int, val y: Int, val beacon: Beacon, val dist: Int = abs(beacon.x - x) + abs(beacon.y - y))
init {
input.map(::numbers).forEach { (sx, sy, bx, by) ->
val beacon = Beacon(bx, by)
beacons += beacon
sensors += Sensor(sx, sy, beacon)
}
}
fun intRangesAtLine(line: Int) = sensors
.mapNotNull { it.atLine(line) }
.sortedBy { it.first }
.fold(mutableListOf<IntRange>()) { acc, intRange ->
val last = acc.removeLastOrNull() ?: intRange
val combine = last.combine(intRange)
if (combine == null) {
acc.add(last)
acc.add(intRange)
} else {
acc.add(combine)
}
acc
}
fun part1(line: Int) = intRangesAtLine(line).sumOf { it.size }.minus(beacons.filter { it.y == line }.size)
fun part2(): Long? = (sensors.minOf { it.y }..sensors.maxOf { it.y })
.asSequence()
.mapNotNull { line ->
intRangesAtLine(line).takeIf { it.size == 2 && it[0].last - it[1].first == -2 }?.let { line to it }
}
.firstOrNull()
?.let { (y, intRages) -> 4000000L * (intRages[0].last + 1) + y }
}
@OptIn(ExperimentalTime::class)
fun main() {
Day15(readInput("Day15_test")).run {
check(part1(10) == 26L)
check(part2() == 56000011L)
}
Day15(readInput("Day15")).run {
measureTimedValue { part1(2000000) }.let(::println)
measureTimedValue { part2() }.let(::println)
}
}
| 0 | Kotlin | 1 | 2 | 39ac1df5542d9cb07a2f2d3448066e6e8896fdc1 | 2,368 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/day16/Day16ChronalClassification.kt | Zordid | 160,908,640 | false | null | package day16
import shared.ElfDeviceCpu
import shared.extractAllInts
import shared.readPuzzle
fun part1(puzzle: List<String>): Int {
val samples = readSamples(puzzle)
return samples.count { (_, couldBe) -> couldBe.size >= 3 }
}
fun part2(puzzle: List<String>): Int {
val samples = readSamples(puzzle)
val allowedMappings = createAllowedMappings(samples, ElfDeviceCpu.instructionSet.keys)
val translationTable = determinePossibleMappingTables(allowedMappings).single()
val instructions = readProgram(puzzle)
val regs = IntArray(4)
instructions.forEach { (opcode, a, b, c) ->
ElfDeviceCpu.instructionSet[translationTable[opcode]]!!(a, b, c, regs)
}
return regs[0]
}
fun readSamples(puzzle: List<String>) =
puzzle.windowed(4, step = 4, partialWindows = true)
.filter { it.size >= 3 && it[0].startsWith("Before:") }
.map { (l1, l2, l3) ->
val before = l1.extractAllInts().toList()
val instruction = l2.extractAllInts().toList()
val after = l3.extractAllInts().toList()
val (opcode, a, b, c) = instruction
opcode to (ElfDeviceCpu.instructionSet.filterValues { mnemonic ->
val reg = before.toIntArray()
try {
mnemonic(a, b, c, reg)
reg.toList() == after
} catch (e: Exception) {
false
}
}.keys)
}
private fun readProgram(puzzle: List<String>) =
puzzle.takeLastWhile { it.isNotEmpty() }.map { it.extractAllInts().toList() }
private fun <T> determinePossibleMappingTables(allowed: Map<Int, Set<T>>): List<Map<Int, T>> {
val nextCandidate = allowed.entries.minByOrNull { (_, v) -> v.size }!!
if (nextCandidate.value.isEmpty())
return emptyList()
val assign = nextCandidate.key
return nextCandidate.value.flatMap { to ->
val assignment = assign to to
val remaining = allowed.reduceBy(assignment)
if (remaining.isNotEmpty())
determinePossibleMappingTables(remaining).filter { it.isNotEmpty() }.map { it + mapOf(assignment) }
else
listOf(mapOf(assignment))
}
}
private fun <T> Map<Int, Set<T>>.reduceBy(assignment: Pair<Int, T>) =
(this - assignment.first).mapValues { (_, v) -> v - assignment.second }
private fun <T> createAllowedMappings(samples: List<Pair<Int, Set<T>>>, all: Set<T>): Map<Int, Set<T>> {
val initialAllowed = all.indices.associateWith { all }.toMutableMap()
return samples.fold(initialAllowed) { acc, pair ->
val (opCode, couldBe) = pair
acc[opCode] = acc[opCode]!! intersect couldBe
acc
}
}
fun main() {
val puzzle = readPuzzle(16)
println(part1(puzzle))
println(part2(puzzle))
} | 0 | Kotlin | 0 | 0 | f246234df868eabecb25387d75e9df7040fab4f7 | 2,815 | adventofcode-kotlin-2018 | Apache License 2.0 |
src/Day08_old.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | import java.util.Stack
import kotlin.math.max
fun main() {
val input = readInput("Day08")
fun part1(input: List<String>): Int {
val map = parseGrid(input)
val left = accMaxFromLeft(map)
val right = accMaxFromRight(map)
val down = accMaxFromDown(map)
val up = accMaxFromUp(map)
val sides = listOf(up, down, left, right)
return map.countIndexed { i, j, v -> sides.any { it[i][j] < v } }
}
fun part2(input: List<String>): Int {
val map = parseGrid(input)
val up = scenicUp(map)
val down = scenicDown(map)
val left = scenicLeft(map)
val right = scenicRight(map)
val sides = listOf(up, down, left, right)
return map.maxOfIndexed { i, j, _ -> sides.map { it[i][j] }.reduce { acc, it -> acc * it } }
}
val testInput = readInput("Day08_test")
println(part1(testInput))
check(part1(testInput) == 21)
println(part2(testInput))
check(part2(testInput) == 8)
println("Part 1")
println(part1(input))
println("Part 2")
println(part2(input))
}
private typealias Grid2D = List<List<Int>>
private fun Grid2D.countIndexed(pred: (i: Int, j: Int, v: Int) -> Boolean): Int {
return sumOfIndexed { i, row -> row.countIndexed { j, it -> pred(i, j, it) } }
}
private fun Grid2D.maxOfIndexed(apply: (i: Int, j: Int, v: Int) -> Int): Int {
return maxOfIndexed { i, row -> row.maxOfIndexed { j, it -> apply(i, j, it) } }
}
private fun parseGrid(map: List<String>): Grid2D {
return map.map { it.map { char -> char - '0' } }
}
private fun accMaxFromLeft(map: Grid2D): Grid2D {
return map.map { row ->
row.dropLast(1).runningFold(-1) { maxSoFar, num -> max(num, maxSoFar) }
}
}
private fun accMaxFromRight(map: Grid2D): Grid2D {
return map.map { row ->
row.reversed().dropLast(1).runningFold(-1) { maxSoFar, num -> max(num, maxSoFar) }.reversed()
}
}
private fun accMaxFromUp(map: Grid2D): Grid2D {
return accMaxFromLeft(map.transpose()).transpose()
}
private fun accMaxFromDown(map: Grid2D): Grid2D {
return accMaxFromRight(map.transpose()).transpose()
}
private fun scenicLeft(map: Grid2D): Grid2D {
return map.map { scenic(it) }
}
private fun scenicRight(map: Grid2D): Grid2D {
return map.map { scenic(it.reversed()).reversed() }
}
private fun scenicUp(map: Grid2D): Grid2D {
return scenicLeft(map.transpose()).transpose()
}
private fun scenicDown(map: Grid2D): Grid2D {
return scenicRight(map.transpose()).transpose()
}
private fun scenic(row: List<Int>): List<Int> {
val s = Stack<Pair<Int, Int>>()
return row.map {
if (s.empty()) {
s.push(it to 1)
return@map 0
}
var popped = 0
while (!s.empty()) {
val top = s.peek()
if (top.first < it) {
s.pop()
popped += top.second
} else {
break
}
}
val seen = popped + (if (s.isEmpty()) 0 else 1)
s.push(it to popped + 1)
return@map seen
}
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 3,118 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day05.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val (seeds, pipeline) = readInput(2023, 5).useLines { sequence ->
val lines = sequence.iterator()
val seeds = lines.next().substringAfter(": ").split(" ").map { it.toLong() }
lines.next()
val pipeline = buildList {
repeat(7) {
lines.next()
add(lines.generateMap())
}
}
seeds to pipeline
}
part1(seeds, pipeline)
part2(seeds, pipeline)
}
private fun part1(seeds: List<Long>, pipeline: List<Map<LongRange, Long>>) {
val lowestLocation = seeds.minOf { seed ->
pipeline.fold(seed) { number, map -> map.getValue(number) }
}
println(lowestLocation)
}
private fun part2(spec: List<Long>, pipeline: List<Map<LongRange, Long>>) {
val lowestLocation = spec.chunked(2).minOf { (start, size) ->
var seed = start
var min = Long.MAX_VALUE
while(seed < start + size) {
var current = seed
var increment = Long.MAX_VALUE
pipeline.forEach { map ->
for ((range, dest) in map) {
if (current in range) {
increment = minOf(increment, range.last - current)
current = dest + current - range.first
return@forEach
}
}
}
min = minOf(min, current) // current -> location
seed += (increment + 1).coerceAtLeast(1)
}
min
}
println(lowestLocation)
}
private fun Iterator<String>.generateMap(): Map<LongRange, Long> = buildMap {
while (hasNext()) {
val line = next()
if (line.isEmpty()) break
val (dest, src, range) = line.split(" ").map { it.toLong() }
put(src..<src + range, dest)
}
}
private fun Map<LongRange, Long>.getValue(key: Long): Long {
for ((range, v) in this) {
if (key in range) {
val diff = key - range.first
return v + diff
}
}
return key
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 2,139 | adventofcode | Apache License 2.0 |
src/Day09.kt | hoppjan | 433,705,171 | false | {"Kotlin": 29015, "Shell": 338} | typealias HeightMap = List<List<Int>>
typealias Basin = List<Position>
typealias UnexploredBasin = MutableList<Position>
fun main() {
fun part1(map: HeightMap) =
map.foldIndexed(mutableListOf<Int>()) { x, acc, row ->
row.forEachIndexed { y, number ->
if (map.hasLowestPointAt(x, y))
acc.add(number + 1)
}
acc
}.sum()
fun part2(map: HeightMap): Int {
val basins = mutableListOf<Basin>()
for (x in map.indices)
for (y in map[x].indices)
if (map.hasLowestPointAt(x, y))
basins.add(map.exploreBasinAt(x, y))
return basins
.sortedBy { it.size }
.takeLast(3) // take largest
.map { it.size }
.product()
}
val day = "09"
val testInput = HeightMapInputReader.read("Day${day}_test")
val input = HeightMapInputReader.read("Day$day")
// part 1
val testSolution1 = 15
val testOutput1 = part1(testInput)
printTestResult(1, testOutput1, testSolution1)
check(testOutput1 == testSolution1)
printResult(1, part1(input).also { check(it == 502) })
// part 2
val testSolution2 = 1134
val testOutput2 = part2(testInput)
printTestResult(2, testOutput2, testSolution2)
check(testOutput2 == testSolution2)
printResult(2, part2(input).also { check(it == 1330560) })
}
data class Position(val x: Int, val y: Int)
val Position.neighbors get() = listOf(
Position(x, y - 1),
Position(x, y + 1),
Position(x - 1, y),
Position(x + 1, y),
)
fun HeightMap.hasLowestPointAt(x: Int, y: Int) = hasLowestPointAt(Position(x, y))
fun HeightMap.hasLowestPointAt(position: Position) =
position.neighbors.all { neighbor ->
getOrMax(position) < getOrMax(neighbor)
}
fun HeightMap.getOrMax(p: Position) = getOrNull(p.x)?.getOrNull(p.y) ?: Int.MAX_VALUE
fun HeightMap.exploreBasinAt(x: Int, y: Int) = exploreBasin(mutableListOf(Position(x, y)))
fun HeightMap.exploreBasin(exploredPart: UnexploredBasin): Basin {
val beforeExploredPart = exploredPart.toList() // makes a copy to compare against
for (basinPosition in beforeExploredPart)
for (neighbor in basinPosition.neighbors)
if (isNewPartOfBasin(neighbor, exploredPart))
exploredPart.add(neighbor)
return if (exploredPart.size > beforeExploredPart.size) // explored something new?
exploreBasin(exploredPart) // here we go recurse again!
else exploredPart
}
fun HeightMap.isNewPartOfBasin(possibleBasinPart: Position, exploredPart: UnexploredBasin) =
exploredPart.containsNot(possibleBasinPart) && getOrMax(possibleBasinPart) < 9
| 0 | Kotlin | 0 | 0 | 04f10e8add373884083af2a6de91e9776f9f17b8 | 2,730 | advent-of-code-2021 | Apache License 2.0 |
app/src/main/kotlin/day02/Day02.kt | W3D3 | 572,447,546 | false | {"Kotlin": 159335} | package day02
import common.InputRepo
import common.readSessionCookie
import common.solve
import util.splitIntoPair
fun main(args: Array<String>) {
val day = 2
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay02Part1, ::solveDay02Part2)
}
fun solveDay02Part1(input: List<String>): Int {
val games = input.map { s -> s.splitIntoPair(" ") }
.map { (opponentChar, playerChar) -> mapOpponentShape(opponentChar) to mapPlayerShape(playerChar) }
return games.sumOf { (opponentMove, playerMove) ->
playGame(
playerMove, opponentMove
).score + playerMove.shapeScore
}
}
fun solveDay02Part2(input: List<String>): Int {
val desiredOutcomes = input.map { s -> s.split(" ")[0] to s.split(" ")[1] }
.map { pair -> mapOpponentShape(pair.first) to mapGameOutcome(pair.second) }
val games = desiredOutcomes.map { (opponentMove, desiredOutcome) ->
opponentMove to getPlayerShape(opponentMove, desiredOutcome)
}
return games.sumOf { (opponentMove, playerMove) ->
playGame(
playerMove, opponentMove
).score + playerMove.shapeScore
}
}
enum class Shape(val shapeScore: Int) {
ROCK(1), PAPER(2), SCISSORS(3),
}
enum class GameOutcome(val score: Int) {
LOSE(0), DRAW(3), WIN(6),
}
fun mapOpponentShape(char: String): Shape {
return when (char) {
"A" -> Shape.ROCK
"B" -> Shape.PAPER
"C" -> Shape.SCISSORS
else -> throw IllegalArgumentException()
}
}
fun mapPlayerShape(char: String): Shape {
return when (char) {
"X" -> Shape.ROCK
"Y" -> Shape.PAPER
"Z" -> Shape.SCISSORS
else -> throw IllegalArgumentException()
}
}
fun mapGameOutcome(char: String): GameOutcome {
return when (char) {
"X" -> GameOutcome.LOSE
"Y" -> GameOutcome.DRAW
"Z" -> GameOutcome.WIN
else -> throw IllegalArgumentException()
}
}
fun playGame(playerShape: Shape, opponentShape: Shape): GameOutcome {
if (playerShape == opponentShape) {
return GameOutcome.DRAW
}
return if ((playerShape.ordinal + 2) % 3 == opponentShape.ordinal) {
GameOutcome.WIN
} else {
GameOutcome.LOSE
}
}
fun getPlayerShape(opponentShape: Shape, outcome: GameOutcome): Shape {
return when (outcome) {
GameOutcome.DRAW -> {
opponentShape
}
GameOutcome.WIN -> {
Shape.values()[(opponentShape.ordinal + 1) % 3]
}
else -> {
Shape.values()[(opponentShape.ordinal + 2) % 3]
}
}
}
| 0 | Kotlin | 0 | 0 | 34437876bf5c391aa064e42f5c984c7014a9f46d | 2,643 | AdventOfCode2022 | Apache License 2.0 |
src/Day07.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | object Day07 {
const val EXPECTED_PART1_CHECK_ANSWER = 95437
const val EXPECTED_PART2_CHECK_ANSWER = 24933642
const val DIR_SIZE_THRESHOLD = 100_000
const val FS_TOTAL_SIZE = 70_000_000
const val FS_NEEDED_FREE_SPACE = 30_000_000
}
sealed class Entry(val name: String)
class File(name: String, val size: Int) : Entry(name)
class Dir(name: String, val parentDir: Dir? = null) : Entry(name) {
private var content: List<Entry> = emptyList()
fun add(entry: Entry): Entry {
content += entry
return this
}
fun dirContent() = content
}
fun main() {
val fileListingRegex = Regex("(\\d+) (\\S+)")
fun parseDirTree(input: List<String>): Dir {
val rootDir = Dir("/")
var currentDir = rootDir
input.drop(1).forEach { entry ->
when {
entry.startsWith("$ cd ..") -> {
if (currentDir.parentDir != null) {
currentDir = currentDir.parentDir!!
}
}
entry.startsWith("$ cd") -> {
val newDir = Dir(entry.substring("$ cd ".length), currentDir)
currentDir.add(newDir)
currentDir = newDir
}
entry.matches(fileListingRegex) -> {
val match = fileListingRegex.matchEntire(entry)
if (match != null) {
currentDir.add(File(match.groupValues[2], match.groupValues[1].toInt()))
}
}
}
}
return rootDir
}
fun dirSizes(dir: Dir, sizes: MutableList<Int>): Int {
var totalDirSize = 0
dir.dirContent().forEach { subEntry ->
totalDirSize += when (subEntry) {
is File -> subEntry.size
is Dir -> dirSizes(subEntry, sizes)
}
}
sizes += totalDirSize
return totalDirSize
}
fun part1(input: List<String>): Int {
val rootDir = parseDirTree(input)
val sizesOfDirs = mutableListOf<Int>()
dirSizes(rootDir, sizesOfDirs)
return sizesOfDirs.filter { it <= Day07.DIR_SIZE_THRESHOLD }.sum()
}
fun part2(input: List<String>): Int {
val rootDir = parseDirTree(input)
val sizesOfDirs = mutableListOf<Int>()
val rootDirSize = dirSizes(rootDir, sizesOfDirs)
val currentFreeSpace = Day07.FS_TOTAL_SIZE - rootDirSize
val needToFreeUp = Day07.FS_NEEDED_FREE_SPACE - currentFreeSpace
return sizesOfDirs.filter { it >= needToFreeUp }.sorted()[0]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == Day07.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day07.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 3,009 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/Day07.kt | JPQuirmbach | 572,636,904 | false | {"Kotlin": 11093} |
fun main() {
fun parseInput(input: List<String>): Dir {
val root = Dir("/")
var current = root
input.drop(1).forEach { line ->
when {
line.startsWith("$ cd ..") -> current = current.parent!!
line.startsWith("$ cd") -> current = current.dirs.first { it.name == line.substringAfter("cd ") }
line.startsWith("dir") -> current.dirs.add(Dir(line.substringAfter("dir "), current))
!line.contains("$") -> current.files.add(File(line.substringBefore(" ").toInt()))
}
}
return root
}
fun part1(input: String): Int {
return parseInput(input.lines())
.allDirs()
.map { it.size() }
.filter { it < 100_000 }
.sum()
}
fun part2(input: String): Int {
val root = parseInput(input.lines())
val fileSystemSize = 70_000_000
val updateSize = 30_000_000
val spaceToFree = updateSize - (fileSystemSize - root.size())
return root.allDirs()
.map { it.size() }
.sorted()
.first { it >= spaceToFree }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
data class File(val size: Int)
data class Dir(
val name: String,
val parent: Dir? = null,
val dirs: MutableList<Dir> = mutableListOf(),
val files: MutableList<File> = mutableListOf()
) {
fun allDirs(): List<Dir> = dirs + dirs.flatMap { it.allDirs() }
fun size(): Int = files.sumOf { it.size } + dirs.sumOf { it.size() }
}
| 0 | Kotlin | 0 | 0 | 829e11bd08ff7d613280108126fa6b0b61dcb819 | 1,802 | advent-of-code-Kotlin-2022 | Apache License 2.0 |
src/day08/Day08.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day08
import readInput
private const val DAY_ID = "08"
fun main() {
fun parseInput(input: List<String>): List<List<Int>> =
input.map { line -> line.map { it.digitToInt() } }
fun findVisibleTreesInInterior(grid: List<List<Int>>): Set<Pair<Int, Int>> {
val m = grid.size
val n = grid[0].size
val visible = hashSetOf<Pair<Int, Int>>()
// last[0] - the last highest tree when going from left-to-right (in a row) or top-to-bottom (in a column)
// last[1] - the last highest tree when going from right-to-left (in a row) or bottom-to-top (in a column)
val last = IntArray(2)
// process interior rows
for (row in 1 until m - 1) {
// scan i-th row in both directions
last[0] = grid[row][0]
last[1] = grid[row][n - 1]
for (left in 1 until n - 1) {
if (grid[row][left] > last[0]) {
last[0] = grid[row][left]
visible += row to left
}
val right = n - left - 1
if (grid[row][right] > last[1]) {
last[1] = grid[row][right]
visible += row to right
}
}
}
// process interior columns
for (col in 1 until n - 1) {
// scan i-th column in both directions
last[0] = grid[0][col]
last[1] = grid[m - 1][col]
for (top in 1 until m - 1) {
if (grid[top][col] > last[0]) {
last[0] = grid[top][col]
visible += top to col
}
val bottom = m - top - 1
if (grid[bottom][col] > last[1]) {
last[1] = grid[bottom][col]
visible += bottom to col
}
}
}
return visible
}
fun part1(input: List<String>): Int {
val grid = parseInput(input)
val m = grid.size
val n = grid[0].size
val visible = findVisibleTreesInInterior(grid)
return 2 * (m + n - 2) /* visible on the edge */ + visible.size /* visible in the interior */
}
fun part2(input: List<String>): Int {
val grid = parseInput(input)
val m = grid.size
val n = grid[0].size
fun viewingDistance(row: Int, col: Int, dx: Int, dy: Int): Int {
var dist = 0
var nextRow = row + dx
var nextCol = col + dy
while (nextRow in 0 until m && nextCol in 0 until n) {
dist++
if (grid[nextRow][nextCol] >= grid[row][col]) {
break
}
nextRow += dx
nextCol += dy
}
return dist
}
val visible = findVisibleTreesInInterior(grid)
val deltas = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) // look up, down, left, right
return visible.maxOf { (row, col) ->
deltas.fold(1) { acc, (dx, dy) -> acc * viewingDistance(row, col, dx, dy) }
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("day${DAY_ID}/Day$DAY_ID")
println(part1(input)) // answer = 1560
println(part2(input)) // answer = 252000
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 3,465 | aoc-2022-in-kotlin | Apache License 2.0 |
2022/src/main/kotlin/day15_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Segment
import utils.Solution
import utils.Vec2i
import utils.mapItems
import kotlin.math.abs
fun main() {
Day15Imp.run()
}
object Day15Imp : Solution<List<Pair<Vec2i, Vec2i>>>() {
override val name = "day15"
override val parser: Parser<List<Pair<Vec2i, Vec2i>>> = Parser.lines.mapItems { line ->
val (sp, bp) = line.split("Sensor at", ": closest beacon is at").map {
it.trim()
.replace("x=", "").replace("y=", "") }
.filter { it.isNotBlank()
}.map { Vec2i.parse(it) }
sp to bp
}
private fun getExclusionSegmentAt(row: Int, sensor: Vec2i, beacon: Vec2i): Segment? {
val yd = abs(sensor.y - row)
val dist = sensor.manhattanDistanceTo(beacon)
if (yd > dist) {
// ignore
return null
}
val left = Vec2i(sensor.x - (dist - yd), row)
val right = Vec2i(sensor.x + (dist - yd), row)
return Segment(left, right)
}
override fun part1(input: List<Pair<Vec2i, Vec2i>>): Int {
// just so our test runs where there's a different row
val row = if (input.size < 18) 10 else 2000000
val sensors = input.map { it.first }.toSet()
val beacons = input.map { it.second }.toSet()
val segments = input.mapNotNull { getExclusionSegmentAt(row, it.first, it.second) }
return ((segments.flatMap { it.points }.toSet() - sensors) - beacons).count()
}
override fun part2(input: List<Pair<Vec2i, Vec2i>>): Long {
// just so our test runs where searchMax is smaller
val searchMax = if (input.size < 18) 20 else 4000000
val sensors = input.map { it.first }.toSet()
val beacons = input.map { it.second }.toSet()
for (y in 0 .. searchMax) {
val segments = input.mapNotNull { getExclusionSegmentAt(y, it.first, it.second) }
var x = 0
val sorted = segments.filter { it.end.x >= 0 && it.start.x <= searchMax }.sortedBy { it.start.x }
for (seg in sorted) {
if (seg.start.x > x) {
return x * 4000000L + y
}
x = maxOf(seg.end.x + 1, x)
if (Vec2i(x, y) in sensors || Vec2i(x, y) in beacons) {
x++
continue
}
}
if (x <= searchMax) {
return x * 4000000L + y
}
}
throw IllegalStateException("should not happen")
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,285 | aoc_kotlin | MIT License |
2015/src/main/kotlin/com/koenv/adventofcode/Day15.kt | koesie10 | 47,333,954 | false | null | package com.koenv.adventofcode
import java.util.*
object Day15 {
fun getHighestScore(input: String): Int {
val (ingredients, combinations) = getCombinations(input)
return combinations.map { ingredients.sumAll(it) }.max()!!
}
fun getBestCalories(input: String): Int {
val (ingredients, combinations) = getCombinations(input)
return combinations.filter { ingredients.sum(it, { it.calories }) == 500 }.map { ingredients.sumAll(it) }.max()!!
}
private fun getCombinations(input: String): Pair<List<Ingredient>, List<List<Int>>> {
val ingredients = input.lines().map {
val result = INGREDIENT_REGEX.find(it)!!
val name = result.groups[1]!!.value
val capacity = result.groups[2]!!.value.toInt()
val durability = result.groups[3]!!.value.toInt()
val flavor = result.groups[4]!!.value.toInt()
val texture = result.groups[5]!!.value.toInt()
val calories = result.groups[6]!!.value.toInt()
Ingredient(name, capacity, durability, flavor, texture, calories)
}
val combinations = arrayListOf<List<Int>>()
val counts = ingredients.map { 0 }
combinations(100, 0, combinations, counts)
return ingredients to combinations
}
data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
)
fun List<Ingredient>.sumAll(amounts: List<Int>): Int {
return sum(amounts, { it.capacity }) * sum(amounts, { it.durability }) * sum(amounts, { it.flavor }) * sum(amounts, { it.texture })
}
fun List<Ingredient>.sum(amounts: List<Int>, property: (Ingredient) -> Int): Int {
var sum = 0
forEachIndexed { i, ingredient ->
sum += property(ingredient) * amounts[i]
}
return Math.max(sum, 0)
}
fun combinations(target: Int, index: Int, results: MutableList<List<Int>>, list: List<Int>) {
for (i in 0..target) {
val newList = ArrayList(list)
newList[index] = i
if (index < list.size - 1 && newList.subList(0, index).sum() <= target) {
combinations(target, index + 1, results, newList)
}
if (index == list.size - 1 && newList.sum() == target) {
results.add(newList)
}
}
}
val INGREDIENT_REGEX = "(.*): capacity (-?\\d+), durability (-?\\d+), flavor (-?\\d+), texture (-?\\d+), calories (-?\\d+)".toRegex()
} | 0 | Kotlin | 0 | 0 | 29f3d426cfceaa131371df09785fa6598405a55f | 2,636 | AdventOfCode-Solutions-Kotlin | MIT License |
src/main/java/leetcode/kotlin/ArrayProblems.kt | Zhaoyy | 110,489,661 | false | {"Java": 248008, "Kotlin": 18188} | package leetcode.kotlin
import java.lang.StringBuilder
import kotlin.math.abs
import kotlin.math.max
fun main(args: Array<String>) {
val problems = ArrayProblems()
// println(problems.maximumProduct(
// intArrayOf(722, 634, -504, -379, 163, -613, -842, -578, 750, 951, -158, 30, -238, -392, -487,
// -797, -157, -374, 999, -5, -521, -879, -858, 382, 626, 803, -347, 903, -205, 57, -342,
// 186, -736, 17, 83, 726, -960, 343, -984, 937, -758, -122, 577, -595, -544, -559, 903,
// -183, 192, 825, 368, -674, 57, -959, 884, 29, -681, -339, 582, 969, -95, -455, -275, 205,
// -548, 79, 258, 35, 233, 203, 20, -936, 878, -868, -458, -882, 867, -664, -892, -687, 322,
// 844, -745, 447, -909, -586, 69, -88, 88, 445, -553, -666, 130, -640, -918, -7, -420, -368,
// 250, -786)))
println(problems.fourSum(intArrayOf(-3, -2, -1, 0, 0, 1, 2, 3), 0))
// println(problems.findErrorNumsBetter(intArrayOf(1, 2, 2, 4)).joinToString(", "))
// println(problems.letterCasePermutationDTS("a1b2"))
val p = IntProblems()
// println(p.longestPalindrome("babad"))
// println(p.validPalindrome("abc"))
// val root = TreeNode(334)
// root.left = TreeNode(277)
// root.right = TreeNode(507)
// root.right.right = TreeNode(678)
// println(p.findTarget(root, 1014))
}
class ArrayProblems {
/**
* https://leetcode.com/problems/minimum-path-sum/description/
*/
fun minPathSum(grid: Array<IntArray>): Int {
val m = grid[0].lastIndex;
for (i in grid.indices) {
for (j in 0..m) {
if (i == 0 && j == 0) {
} else if (i == 0 && j != 0) {
grid[i][j] += grid[i][j - 1]
} else if (j == 0 && i != 0) {
grid[i][j] += grid[i - 1][j]
} else {
grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1])
}
}
}
return grid[grid.lastIndex][m]
}
/**
* https://leetcode.com/problems/4sum/description/
*/
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val ans = ArrayList<List<Int>>()
nums.sort()
for (i in 0..nums.size - 4) {
// can do better
if (i > 0 && nums[i] == nums[i - 1]) continue
for (j in i + 1..nums.size - 3) {
// can do better
if (j > i + 1 && nums[j] == nums[j - 1]) continue
val diff = target - nums[i] - nums[j]
var l = j + 1
var r = nums.lastIndex
while (l < r) {
val temp = nums[l] + nums[r]
when {
temp == diff -> {
ans.add(listOf(nums[i], nums[j], nums[l], nums[r]))
while (l < r && nums[l] == nums[l + 1]) l++
while (l < r && nums[r] == nums[r - 1]) r--
l++
r--
}
temp < diff -> {
while (l < r && nums[l] == nums[l + 1]) l++
l++
}
else -> {
while (l < r && nums[r] == nums[r - 1]) r--
r--
}
}
}
}
}
return ans
}
/**
* https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
*/
private val keyBoard = arrayOf(
emptyArray(),
emptyArray(),
arrayOf('a', 'b', 'c'),
arrayOf('d', 'e', 'f'),
arrayOf('g', 'h', 'i'),
arrayOf('j', 'k', 'l'),
arrayOf('m', 'n', 'o'),
arrayOf('p', 'q', 'r', 's'),
arrayOf('t', 'u', 'v'),
arrayOf('w', 'x', 'y', 'z')
)
fun letterCombinations(digits: String): List<String> {
val ans = ArrayList<String>()
dfsLetterCombinations(digits, StringBuilder(), ans, 0)
return ans
}
private fun dfsLetterCombinations(
digits: String,
temp: StringBuilder,
list: MutableList<String>,
step: Int
) {
if (step == digits.length) {
if (temp.isNotEmpty()) list.add(temp.toString())
return
}
val num = digits[step] - '0'
val chars = keyBoard[num]
val len = temp.length
if (chars.isNotEmpty()) {
for (c in chars) {
temp.setLength(len)
dfsLetterCombinations(digits, temp.append(c), list, step + 1)
}
} else {
dfsLetterCombinations(digits, temp, list, step + 1)
}
}
/**
* https://leetcode.com/problems/3sum-closest/description/
*/
fun threeeSumClosestB(nums: IntArray, target: Int): Int {
if (nums.size <= 3) return nums.sum()
nums.sort()
var ans = nums.take(3).sum()
val n = nums.lastIndex
for (i in 0..nums.lastIndex - 2) {
var l = i + 1
var r = n
while (l < r) {
val sum = nums[i] + nums[l] + nums[r]
if (Math.abs(target - ans) > Math.abs(target - sum)) {
ans = sum
if (ans == target) return ans
}
if (sum > target) {
r--
} else {
l++
}
}
}
return ans
}
fun threeSumClosest(nums: IntArray, target: Int): Int {
if (nums.size == 3) return getThreeSum(nums, 0)
nums.sort()
var l = 0
var r = nums.size - 3
var sumL = 0
var sumR = 0
while (l < r) {
sumL = getThreeSum(nums, l)
sumR = getThreeSum(nums, r)
val mid = (l + r) / 2
val sumM = getThreeSum(nums, mid)
when {
sumL >= target -> return sumL
sumR <= target -> return sumR
sumM == target -> return sumM
sumM < target -> l = mid + 1
else -> r = mid - 1
}
}
return closed(sumL, sumR, target)
}
private fun getThreeSum(nums: IntArray, start: Int): Int {
return nums[start] + nums[start + 1] + nums[start + 2]
}
private fun closed(a: Int, b: Int, target: Int): Int {
return if (abs(a - target) < abs(b - target)) {
a
} else {
b
}
}
/**
* https://leetcode.com/problems/3sum/description/
*/
fun threeSum(nums: IntArray): List<List<Int>> {
nums.sort()
val result = ArrayList<List<Int>>()
for (i in 0..nums.size - 3) {
if (i == 0 || nums[i] != nums[i - 1]) {
var l = i + 1
var r = nums.lastIndex
val diff = -nums[i]
while (l < r) {
val sum = nums[l] + nums[r]
when {
sum == diff -> {
result.add(arrayListOf(nums[i], nums[l], nums[r]))
while (l < r && nums[l] == nums[l + 1]) l++
while (l < r && nums[r] == nums[r - 1]) r--
l++
r--
}
sum > diff -> {
while (r - 1 > 0 && nums[r] == nums[r - 1]) r--
r--
}
sum < diff -> {
while (l + 1 < nums.lastIndex && nums[l] == nums[l + 1]) l++
l++
}
}
}
}
}
return result
}
/**
* https://leetcode.com/problems/rotate-string/description/
*/
fun rotateString(A: String, B: String): Boolean {
if (A.length != B.length) return false
val sb = StringBuilder()
for (i in B.indices) {
if (B[i] == A[0]) {
sb.setLength(0)
sb.append(B.substring(i, B.length)).append(B.substring(0, i))
if (sb.toString() == A) return true
}
}
return false
}
/**
* https://leetcode.com/problems/letter-case-permutation/description/
*/
fun letterCasePermutationDTS(S: String): List<String> {
val result = ArrayList<String>()
dfsHelper(S, result, 0)
return result
}
private fun dfsHelper(s: String, list: MutableList<String>, pos: Int) {
if (s.length == pos) {
list.add(s)
return
}
if (s[pos] > '9') {
val chars = s.toCharArray()
chars[pos] = chars[pos].toLowerCase()
dfsHelper(String(chars), list, pos + 1)
chars[pos] = chars[pos].toUpperCase()
dfsHelper(String(chars), list, pos + 1)
} else {
dfsHelper(s, list, pos + 1)
}
}
fun letterCasePermutation(S: String): List<String> {
val result = ArrayList<String>()
result.add(S)
val buffer = StringBuilder()
for (i in S.indices) {
if (S[i] > '9') {
val p = letterPermutation(S[i])
val n = result.lastIndex
for (j in 0..n) {
buffer.setLength(0)
buffer.append(result[j])
buffer.setCharAt(i, p)
result.add(buffer.toString())
}
}
}
return result
}
private fun letterPermutation(c: Char): Char {
return if (c in 'a'..'z') {
'A' + (c - 'a')
} else {
'a' + (c - 'A')
}
}
/**
* https://leetcode.com/problems/repeated-string-match/description/
*/
fun repeatedStringMatch(A: String, B: String): Int {
val sb = StringBuilder(A)
for (r in 1..(B.length / A.length + 2)) {
if (sb.contains(B)) {
return r
}
sb.append(A)
}
return -1
}
/**
* https://leetcode.com/problems/baseball-game/description/
*/
fun calPoints(ops: Array<String>): Int {
val rPoints = ArrayList<Int>()
for (p in ops) {
when (p) {
"+" -> {
val lastIndex = rPoints.lastIndex
rPoints.add(rPoints[lastIndex] + rPoints[lastIndex - 1])
}
"D" -> {
rPoints.add(rPoints[rPoints.lastIndex] * 2)
}
"C" -> {
rPoints.removeAt(rPoints.lastIndex)
}
else -> rPoints.add(p.toInt())
}
}
return rPoints.sum()
}
/**
* https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/
*/
fun findLengthOfLCIS(nums: IntArray): Int {
if (nums.size < 2) return nums.size
var result = 0
var count = 1
var last = nums[0]
for (i in 1..nums.lastIndex) {
if (nums[i] > last) {
count++
} else {
result = max(count, result)
count = 1
}
last = nums[i]
}
return max(count, result)
}
/**
* https://leetcode.com/problems/non-decreasing-array/description/
*/
fun checkPossibility(nums: IntArray): Boolean {
if (nums.isEmpty() || nums.size == 1 || nums.size == 2) {
return true
}
var found = false
var i = 0
while (i < nums.lastIndex) {
if (nums[i] > nums[i + 1]) {
if (found) return false
else {
found = true
if (i > 0 && nums[i + 1] < nums[i - 1]) {
nums[i + 1] = nums[i]
}
}
}
i++
}
return true
}
/**
* https://leetcode.com/problems/image-smoother/description/
*/
fun imageSmoother(M: Array<IntArray>): Array<IntArray> {
val result = Array(M.size, { i -> IntArray(M[i].size) })
val t = arrayOf(-1, 0, 1)
for (x in M.indices) {
for (y in M[x].indices) {
var sum = 0
var count = 0
for (tx in t) {
for (ty in t) {
val a = x + tx
val b = y + ty
if (a >= 0 && b >= 0 && a < M.size && b < M[x].size) {
sum += M[a][b]
count++
}
}
}
if (count > 0) {
result[x][y] = sum / count
}
}
}
return result
}
/**
* https://leetcode.com/problems/judge-route-circle/description/
*/
fun judgeCircle(moves: String): Boolean {
var x = 0
var y = 0
moves.forEach {
when (it) {
'L' -> x--
'R' -> x++
'U' -> y++
'D' -> y--
}
}
return x == 0 && y == 0
}
/**
* https://leetcode.com/problems/set-mismatch/description/
*/
fun findErrorNumsBetter(nums: IntArray): IntArray {
val result = IntArray(2)
val extraArray = IntArray(nums.size + 1)
for (n in nums) {
if (extraArray[n] == 1) {
result[0] = n
} else {
extraArray[n] = 1
}
}
for (i in 1 until extraArray.size) {
if (extraArray[i] == 0) {
result[1] = i
break
}
}
return result
}
fun findErrorNums(nums: IntArray): IntArray {
var extra = 0
var miss = 0
nums.sort()
for (i in 0 until nums.lastIndex) {
if (miss > 0 && extra > 0) break
if (miss == 0 && nums[i] != i + 1 && nums[i + 1] != i + 1) {
miss = i + 1
}
if (extra == 0 && nums[i] == nums[i + 1]) {
extra = nums[i]
}
}
return intArrayOf(extra, if (miss > 0) miss else nums.size)
}
/**
* https://leetcode.com/problems/maximum-average-subarray-i/description/
*/
fun findMaxAverage(nums: IntArray, k: Int): Double {
var lastSum = (0 until k).sumBy { nums[it] }
var maxSum = lastSum
for (i in 1..nums.size - k) {
lastSum = lastSum - nums[i - 1] + nums[i + k - 1]
maxSum = Math.max(maxSum, lastSum)
}
return maxSum.toDouble() / k
}
/**
* https://leetcode.com/problems/maximum-product-of-three-numbers/description/
*/
fun maximumProduct(nums: IntArray): Int {
nums.sort()
val last = nums.lastIndex
val t = nums[last - 1] * nums[last] * nums[last - 2]
val h = nums[0] * nums[1] * nums[last]
return if (t > h) {
t
} else {
h
}
}
} | 0 | Java | 0 | 0 | 3f801c8f40b5bfe561c5944743a779dad2eca0d3 | 12,985 | leetcode | Apache License 2.0 |
src/day15/Day15.kt | EndzeitBegins | 573,569,126 | false | {"Kotlin": 111428} | package day15
import readInput
import readTestInput
import kotlin.math.absoluteValue
private data class Position(val x: Int, val y: Int)
private data class Sensor(val position: Position) {
constructor(x: Int, y: Int) : this(Position(x, y))
}
private data class Beacon(val position: Position) {
constructor(x: Int, y: Int) : this(Position(x, y))
}
private data class ScannedArea(val center: Position, val radius: Int)
private fun distanceBetween(a: Position, b: Position): Int {
return (a.x - b.x).absoluteValue + (a.y - b.y).absoluteValue
}
private infix fun Position.isIn(area: ScannedArea): Boolean {
return distanceBetween(this, area.center) <= area.radius
}
private fun List<String>.toSensorBeaconPairs(): List<Pair<Sensor, Beacon>> {
val regex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex()
return map { line ->
val result = regex.matchEntire(line)
val (sensorX, sensorY, beaconX, beaconY) = checkNotNull(result).destructured
Sensor(sensorX.toInt(), sensorY.toInt()) to Beacon(beaconX.toInt(), beaconY.toInt())
}
}
private fun List<ScannedArea>.findNonScannedPosition(searchDistance: Int): Position {
val scannedAreas = this
for (scannedArea in scannedAreas) {
val sensor = scannedArea.center
val radius = scannedArea.radius
val borderDistance = radius + 1
for (offset in (0..borderDistance)) {
val positionsToInspect = listOf(
Position(sensor.x - borderDistance + offset, sensor.y + offset),
Position(sensor.x - borderDistance + offset, sensor.y - offset),
Position(sensor.x + borderDistance - offset, sensor.y + offset),
Position(sensor.x + borderDistance - offset, sensor.y - offset),
)
val nonScannedPosition: Position? = positionsToInspect.firstOrNull { position->
position.x >= 0 && position.y >= 0
&& position.x <= searchDistance && position.y <= searchDistance
&& scannedAreas.none { area -> position isIn area }
}
if (nonScannedPosition != null)
return nonScannedPosition
}
}
error("No non-scanned position found!")
}
private fun part1(input: List<String>, scanY: Int): Int {
val sensorBeaconPairs = input.toSensorBeaconPairs()
val scannedAreas = sensorBeaconPairs.map { (sensor, beacon) ->
ScannedArea(sensor.position, distanceBetween(sensor.position, beacon.position))
}
val minX = scannedAreas.minOf { scannedArea -> scannedArea.center.x - scannedArea.radius }
val maxX = scannedAreas.maxOf { scannedArea -> scannedArea.center.x + scannedArea.radius }
val scannedPositions = (minX..maxX)
.map { x -> Position(x = x, y = scanY) }
.count { position ->
sensorBeaconPairs.none { (_, beacon) -> beacon.position == position }
&& scannedAreas.any { scannedArea -> position isIn scannedArea }
}
return scannedPositions
}
private fun part2(input: List<String>, searchDistance: Int): Long {
val sensorBeaconPairs = input.toSensorBeaconPairs()
val scannedAreas = sensorBeaconPairs.map { (sensor, beacon) ->
ScannedArea(sensor.position, distanceBetween(sensor.position, beacon.position))
}
val nonScannedPosition = scannedAreas.findNonScannedPosition(searchDistance)
return 4_000_000L * nonScannedPosition.x + nonScannedPosition.y
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day15")
check(part1(testInput, scanY = 10) == 26)
check(part2(testInput, searchDistance = 20) == 56_000_011L)
val input = readInput("Day15")
println(part1(input, scanY = 2_000_000))
println(part2(input, searchDistance = 4_000_000))
}
| 0 | Kotlin | 0 | 0 | ebebdf13cfe58ae3e01c52686f2a715ace069dab | 3,914 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day5/Day5.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day5
import execute
import readAllText
import splitBy
import wtf
fun main() {
val input = readAllText("local/day5_input.txt")
val test = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent()
execute(::part1, test)
execute(::part1, input)
execute(::part2, test)
execute(::part2, input)
}
private val regex = "move (\\d+) from (.) to (.)".toRegex()
private fun parse(matchResult: MatchResult) =
matchResult.destructured.let { (a, b, c) -> Triple(a.toInt(), b.single(), c.single()) }
fun part1(input: String) = solve(input, moveAllAtOnce = false)
fun part2(input: String) = solve(input, moveAllAtOnce = true)
private fun solve(input: String, moveAllAtOnce: Boolean): String {
val (stacksSection, commands) = input.lineSequence().splitBy(String::isBlank).toList()
val stacks = parseStacks(stacksSection).toMutableMap()
commands.map { regex.matchEntire(it)?.let(::parse) ?: wtf(it) }
.forEach { (count, from, to) -> stacks.move(from, to, count, moveAllAtOnce) }
return stacks.toList().sortedBy { it.first }.map { it.second.last() }.joinToString("")
}
private fun parseStacks(stacksSection: List<String>): Map<Char, String> =
stacksSection.reversed().map { it.chunked(4) }
.let { parsed ->
val head = parsed.first()
val tail = parsed.drop(1)
head.mapIndexed { index, stack ->
val stackId = stack.trim().single()
val stackContent = buildString {
tail.map { it[index] }.forEach { if (it.isNotBlank()) append(it[1]) }
}
stackId to stackContent
}
}
.toMap()
private fun MutableMap<Char, String>.move(from: Char, to: Char, count: Int, moveAllAtOnce: Boolean) {
val crates = this[from]!!.takeLast(count)
this[from] = this[from]!!.dropLast(count)
this[to] = this[to]!! + if (moveAllAtOnce) crates else crates.reversed()
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 2,079 | advent-of-code-2022 | MIT License |
src/main/kotlin/day11.kt | kevinrobayna | 436,414,545 | false | {"Ruby": 195446, "Kotlin": 42719, "Shell": 1288} | import java.util.stream.Collectors
fun day11ProblemReader(text: String): List<List<String>> = text
.split('\n')
.stream()
.map { line ->
line.trim()
.split("")
.stream()
.filter { it != "" }
.collect(Collectors.toList())
}
.collect(Collectors.toList())
// https://adventofcode.com/2020/day/11
class Day11(
private val seats: List<List<String>>,
private val threshold: Int,
private val lookFar: Boolean = false
) {
companion object {
const val FREE = "L"
const val FLOOR = "."
const val OCCUPIED = "#"
val neighbours = listOf(
Pair(-1, -1),
Pair(-1, 0),
Pair(-1, 1),
Pair(1, -1),
Pair(1, 0),
Pair(1, 1),
Pair(0, -1),
Pair(0, 1),
)
}
fun solve(): Int {
var changes: Int
var originalSeats: MutableList<MutableList<String>> = seats.map { it.toMutableList() }.toMutableList()
var seatsToChange: MutableList<MutableList<String>>
do {
changes = 0
seatsToChange = originalSeats.map { it.toMutableList() }.toMutableList()
for (row in seats.indices) {
for (column in seats[row].indices) {
if (originalSeats[row][column] == FLOOR) {
continue
}
val adjacentSeats = exploreNeighbours(originalSeats, row, column)
// rule n1
val emptySeats = adjacentSeats.filter { it in listOf(FLOOR, FREE) }.size
if (originalSeats[row][column] == FREE && emptySeats == neighbours.size) {
seatsToChange[row][column] = OCCUPIED
changes += 1
}
// rule n2
val usedSeats = adjacentSeats.filter { it in listOf(OCCUPIED) }.size
if (originalSeats[row][column] == OCCUPIED && usedSeats >= threshold) {
seatsToChange[row][column] = FREE
changes += 1
}
}
}
originalSeats = seatsToChange.map { it.toMutableList() }.toMutableList()
} while (changes != 0)
return originalSeats.map { line -> line.filter { it == OCCUPIED }.count() }.sum()
}
private fun exploreNeighbours(map: List<List<String>>, x: Int, y: Int): List<String> {
return neighbours.map { (i, j) ->
findSeat(map, Pair(x, y), Pair(i, j))
}
}
private fun findSeat(map: List<List<String>>, current: Pair<Int, Int>, next: Pair<Int, Int>): String {
val (x, y) = current
val (i, j) = next
val seat = listOf(FREE, OCCUPIED)
return if (x + i < 0 || y + j < 0) FLOOR
else if (x + i > map.size - 1 || y + j > map[0].size - 1) FLOOR
else {
if (!lookFar) map[x + i][y + j]
else if (map[x + i][y + j] in seat) map[x + i][y + j]
else findSeat(map, Pair(x + i, y + j), Pair(i, j))
}
}
}
fun main() {
val problem = day11ProblemReader(Day10::class.java.getResource("day11.txt").readText())
println("solution = ${Day11(problem, 4).solve()}")
println("solution part2 = ${Day11(problem, 5, true).solve()}")
} | 0 | Ruby | 0 | 0 | 9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577 | 3,382 | adventofcode_2020 | MIT License |
src/poyea/aoc/mmxxii/day18/Day18.kt | poyea | 572,895,010 | false | {"Kotlin": 68491} | package poyea.aoc.mmxxii.day18
import poyea.aoc.utils.readInput
data class Point(val x: Int, val y: Int, val z: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y, z + other.z)
fun neighbours() = listOf(
copy(x = x - 1),
copy(x = x + 1),
copy(y = y - 1),
copy(y = y + 1),
copy(z = z - 1),
copy(z = z + 1),
)
}
fun part1(input: String): Int {
val listOfPoints = input.split("\n").map { it ->
val (x, y, z) = it.split(",", limit = 3)
Point(x.toInt(), y.toInt(), z.toInt())
}
var total = 0
for (point in listOfPoints) {
total += point.neighbours().count { it !in listOfPoints }
}
return total
}
fun part2(input: String): Int {
val listOfPoints = input.split("\n").map { it ->
val (x, y, z) = it.split(",", limit = 3)
Point(x.toInt(), y.toInt(), z.toInt())
}
val minX = listOfPoints.minBy { it.x }.x
val maxX = listOfPoints.maxBy { it.x }.x
val minY = listOfPoints.minBy { it.y }.y
val maxY = listOfPoints.maxBy { it.y }.y
val minZ = listOfPoints.minBy { it.z }.z
val maxZ = listOfPoints.maxBy { it.z }.z
val outside = buildSet {
val queue = mutableListOf(Point(minX - 1, minY - 1, minZ - 1).also { add(it) })
while (queue.isNotEmpty()) {
for (neighbour in queue.removeLast().neighbours()) {
if (neighbour.x in minX - 1..maxX + 1
&& neighbour.y in minY - 1..maxY + 1
&& neighbour.z in minZ - 1..maxZ + 1
&& neighbour !in listOfPoints
) {
if (add(neighbour)) {
queue.add(neighbour)
}
}
}
}
}
var total = 0
for (point in listOfPoints) {
total += point.neighbours().count { it in outside }
}
return total
}
fun main() {
println(part1(readInput("Day18")))
println(part2(readInput("Day18")))
}
| 0 | Kotlin | 0 | 1 | fd3c96e99e3e786d358d807368c2a4a6085edb2e | 2,035 | aoc-mmxxii | MIT License |
src/main/kotlin/day7/Day7SumOfItsParts.kt | Zordid | 160,908,640 | false | null | package day7
import shared.readPuzzle
fun part1(input: List<String>): Any {
val required = prepareData(input)
val order = mutableListOf<Char>()
while (required.filter { (step, requires) ->
!order.contains(step) && order.containsAll(requires)
}.keys.minOrNull()?.also {
order.add(it)
} != null);
return order.joinToString("")
}
fun Map<Char, MutableSet<Char>>.nextToWorkOn(): List<Char> {
return this.filter { it.value.isEmpty() }.keys.sorted()
}
fun part2(input: List<String>, maxWorkers: Int = 5, baseWork: Int = 60): Any {
val instructions = input.map { line -> line.split(' ').let { it[7][0] to it[1][0] } }
val required = mutableMapOf<Char, MutableSet<Char>>()
instructions.forEach { (step, requires) ->
required.getOrPut(requires) { mutableSetOf() }
required.getOrPut(step) { mutableSetOf() }.add(requires)
}
val order = StringBuilder()
val workers = mutableMapOf<Char, Int>()
var time = 0
while (true) {
while (workers.size == maxWorkers || (required.nextToWorkOn() - workers.keys).isEmpty()) {
val nextFinished = workers.minBy { it.value }
workers.remove(nextFinished.key)
required.forEach { it.value.remove(nextFinished.key) }
required.remove(nextFinished.key)
time = nextFinished.value
order.append(nextFinished.key)
println(order)
if (required.isEmpty())
return time
}
val workOn = (required.nextToWorkOn() - workers.keys).first()
workers[workOn] = time + baseWork + (workOn - 'A' + 1)
}
}
fun prepareData(input: List<String>): Map<Char, Set<Char>> {
val instructions = input.map { line -> line.split(' ').let { it[7][0] to it[1][0] } }
val required = mutableMapOf<Char, MutableSet<Char>>()
instructions.forEach { (step, requires) ->
required.getOrPut(requires) { mutableSetOf() }
required.getOrPut(step) { mutableSetOf() }.add(requires)
}
return required
}
fun Char.effort(): Int = this - 'A' + 1
/**
* This is a reimplementation of the algorithm free of the double inner loop
*/
fun part2(requirements: Map<Char, Set<Char>>, maxWorkers: Int = 5, baseWork: Int = 60): Any {
val order = mutableListOf<Char>()
val workers = mutableMapOf<Char, Int>()
while (true) {
val time = workers.values.minOrNull() ?: 0
val finishedSteps = workers.filterValues { it == time }.keys
order.addAll(finishedSteps.sorted())
workers -= finishedSteps
val availableSteps = requirements.filter { (step, requiredSteps) ->
!order.contains(step) &&
!workers.keys.contains(step) &&
order.containsAll(requiredSteps)
}.keys
if (availableSteps.isEmpty() && workers.isEmpty())
return time
val freeWorkers = maxWorkers - workers.size
availableSteps.sorted().asSequence().take(freeWorkers).forEach { step ->
workers[step] = time + baseWork + step.effort()
}
}
}
fun main() {
val stepRequires = readPuzzle(7)
val requirements = prepareData(stepRequires)
println(part1(stepRequires))
println(part2(stepRequires))
println(part2(requirements))
} | 0 | Kotlin | 0 | 0 | f246234df868eabecb25387d75e9df7040fab4f7 | 3,323 | adventofcode-kotlin-2018 | Apache License 2.0 |
gcj/y2020/kickstart_c/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2020.kickstart_c
private fun solve(): Long {
val (n, q) = readInts()
val ft = FenwickTree(n)
val ftCoef = FenwickTree(n)
fun set(i: Int, value: Int) {
ft[i] = minusOnePow(i) * value
ftCoef[i] = minusOnePow(i) * value * (i + 1)
}
fun query(start: Int, end: Int) = (ftCoef.sum(start, end) - ft.sum(start, end) * start) * minusOnePow(start)
readInts().forEachIndexed(::set)
var ans = 0L
repeat(q) {
val (op, xIn, yIn) = readStrings()
val x = xIn.toInt() - 1; val y = yIn.toInt()
if (op == "U") set(x, y) else ans += query(x, y)
}
return ans
}
class FenwickTree(n: Int) {
val t = LongArray(n)
fun add(i: Int, value: Long) {
var j = i
while (j < t.size) {
t[j] += value
j += j + 1 and -(j + 1)
}
}
fun sum(i: Int): Long {
var j = i - 1
var res = 0L
while (j >= 0) {
res += t[j]
j -= j + 1 and -(j + 1)
}
return res
}
fun sum(start: Int, end: Int): Long = sum(end) - sum(start)
operator fun get(i: Int): Long = sum(i, i + 1)
operator fun set(i: Int, value: Int) = add(i, value - get(i))
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
fun minusOnePow(i: Int) = 1 - ((i and 1) shl 1)
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,366 | competitions | The Unlicense |
src/Day08.kt | qmchenry | 572,682,663 | false | {"Kotlin": 22260} | fun main() {
fun condensedString(map: List<List<Int>>): String {
return map.map { it.joinToString(" ") }.joinToString("\n")
}
fun condensedString(map: List<List<Boolean>>): String {
return map.map {
it.map { if (it) "#" else "." }.joinToString("")
}.joinToString("\n")
}
fun buildMap(input: List<String>): List<List<Int>> {
return input.map {
it.map { char -> char.digitToInt() }
}
}
fun isHidden(input: List<Int>): List<Boolean> {
var tallest = input.first()
return input.map {
if (it > tallest) {
tallest = it
false
} else {
true
}
}
}
fun isHiddenBidirectionally(input: List<Int>): List<Boolean> {
val forward = isHidden(input)
val backward = isHidden(input.reversed()).reversed()
return forward.zip(backward).map { (f, b) -> f && b }
}
fun visibility(input: List<Int>): Int {
val first = input.first()
val lineOfSight = input.drop(1)
val keepIndex = lineOfSight.indexOfFirst { first <= it }
val keep = if (keepIndex == -1) lineOfSight.size else keepIndex + 1
val trees = input.drop(1).take(keep)
return trees.count()
}
fun visibilityScore(input: List<Int>): List<Int> {
return input.mapIndexed { index, _ ->
visibility(input.drop(index))
}
}
fun visibilityScoreBidirectional(input: List<Int>): List<Int> {
val forward = visibilityScore(input)
val backward = visibilityScore(input.reversed()).reversed()
return forward.zip(backward).map { (f, b) -> f * b }
}
fun <E> transpose(input: List<List<E>>): List<List<E>> {
fun <E> List<E>.head(): E = this.first()
fun <E> List<E>.tail(): List<E> = this.takeLast(this.size - 1)
fun <E> E.append(xs: List<E>): List<E> = listOf(this).plus(xs)
input.filter { it.isNotEmpty() }.let { ys ->
return when (ys.isNotEmpty()) {
true -> ys.map { it.head() }.append(transpose(ys.map { it.tail() }))
else -> emptyList()
}
}
}
fun part1(input: List<String>): Int {
val map = buildMap(input)
val rowWise = map.map { isHiddenBidirectionally(it) }
val columnWise = transpose(map).map { isHiddenBidirectionally(it) }
val bothWays = rowWise.zip(transpose(columnWise)).map { (r, c) -> r.zip(c).map { (a, b) -> a && b } }
val inner = bothWays.map { it.drop(1).dropLast(1) }.drop(1).dropLast(1)
val visibleCount = inner.flatten().count { !it }
val outerRing = (map.size + map.first().size) * 2 - 4
return visibleCount + outerRing
}
fun part2(input: List<String>): Int {
val map = buildMap(input)
val rowWise = map.map { visibilityScoreBidirectional(it) }
val columnWise = transpose(map).map { visibilityScoreBidirectional(it) }
val bothWays = rowWise.zip(transpose(columnWise)).map { (r, c) -> r.zip(c).map { (a, b) -> a * b } }
return bothWays.maxOf { it.max() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_sample")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val realInput = readInput("Day08_input")
println("Part 1: ${part1(realInput)}")
println("Part 2: ${part2(realInput)}")
}
| 0 | Kotlin | 0 | 0 | 2813db929801bcb117445d8c72398e4424706241 | 3,507 | aoc-kotlin-2022 | Apache License 2.0 |
15/part_one.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
import java.util.PriorityQueue
fun readInput() : Grid {
val input = File("input.txt")
.readText()
.split("\r\n")
.filter { it.isNotEmpty() }
.map { row -> row.map { it.digitToInt() }}
return Grid(input)
}
class Grid(mat : List<List<Int>>) {
companion object {
val deltaX = listOf(1, 0, -1, 0)
val deltaY = listOf(0, 1, 0, -1)
const val INF = 1e9.toInt()
const val DIRECTIONS = 4
}
private val mat : List<List<Int>>
private val rows : Int
private val cols : Int
init {
this.mat = mat
rows = mat.size
cols = mat[0].size
}
fun minCostToEnd() : Int {
return dijkstra(0, 0, rows - 1, cols - 1)
}
private fun dijkstra(startX : Int, startY : Int, endX : Int, endY : Int) : Int {
val distance = Array(rows) { IntArray(cols) { INF }}
distance[0][0] = 0
val pq = PriorityQueue()
{ o1: Triple<Int, Int, Int>, o2: Triple<Int, Int, Int> ->
if (o1.first < o2.first) -1 else 1
}
pq.add(Triple(0, startX, startY))
while(pq.isNotEmpty()) {
val (cost, x, y) = pq.peek()
pq.remove()
if (cost > distance[x][y]) continue
for (dir in 0 until DIRECTIONS) {
val nx = x + deltaX[dir]
val ny = y + deltaY[dir]
if (isIn(nx, ny)) {
if (distance[nx][ny] > distance[x][y] + mat[nx][ny]) {
distance[nx][ny] = distance[x][y] + mat[nx][ny]
pq.add(Triple(distance[nx][ny], nx, ny))
}
}
}
}
return distance[endX][endY]
}
private fun isIn(x : Int, y : Int) : Boolean {
return x in 0 until rows && y in 0 until cols
}
}
fun solve(grid : Grid) : Int {
return grid.minCostToEnd()
}
fun main() {
val grid = readInput()
val ans = solve(grid)
println(ans)
}
| 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 2,045 | advent-of-code-2021 | MIT License |
src/Day02.kt | derivz | 575,340,267 | false | {"Kotlin": 6141} | val rules = mapOf(
"A" to mapOf("X" to 3, "Y" to 6, "Z" to 0),
"B" to mapOf("X" to 0, "Y" to 3, "Z" to 6),
"C" to mapOf("X" to 6, "Y" to 0, "Z" to 3),
)
val extraPoints = mapOf(
"X" to 1, "Y" to 2, "Z" to 3
)
val desiredPoints = mapOf(
"X" to 0, "Y" to 3, "Z" to 6
)
fun main() {
fun part1(lines: List<String>): Int {
return lines.map { line ->
val (hisMove, myMove) = line.split(" ")
val points = rules[hisMove]!![myMove]!! + extraPoints[myMove]!!
points
}.sum()
}
fun part2(lines: List<String>): Int {
return lines.map { line ->
val (hisMove, desiredOutput) = line.split(" ")
val desiredPoints = desiredPoints[desiredOutput]!!
val myMove = rules[hisMove]!!.filterValues { it == desiredPoints }.keys.first()
val points = rules[hisMove]!![myMove]!! + extraPoints[myMove]!!
points
}.sum()
}
val lines = readLines("Day02")
println(part1(lines))
println(part2(lines))
}
| 0 | Kotlin | 0 | 0 | 24da2ff43dc3878c4e025f5b737dca31913f40a5 | 1,045 | AoC2022.kt | Apache License 2.0 |
src/main/kotlin/Day13.kt | akowal | 434,506,777 | false | {"Kotlin": 30540} | fun main() {
println(Day13.solvePart1())
Day13.solvePart2()
}
object Day13 {
private val input = readInput("day13")
private val points = input.takeWhile { it.isNotBlank() }
.map { it.toIntArray() }
.map { (x, y) -> Point(x, y) }
private val folds = input.takeLastWhile { it.isNotBlank() }
.map { it.substringAfter("fold along ") }
.map { it.split('=') }
.map { (axis, value) ->
when (axis) {
"x" -> Fold.X(value.toInt())
"y" -> Fold.Y(value.toInt())
else -> error("xoxoxo")
}
}
fun solvePart1() = fold(points.toMutableSet(), folds.take(1)).size
fun solvePart2() {
val result = fold(points.toMutableSet(), folds)
val width = result.maxOf { it.x } + 1
result.groupBy { it.y }.toSortedMap().forEach { (_, row) ->
val line = CharArray(width) { ' ' }
row.forEach { line[it.x] = '#' }
println(line)
}
}
private fun fold(points: MutableSet<Point>, folds: List<Fold>): Set<Point> {
folds.forEach { fold ->
points.filter(fold::filter).forEach {
points -= it
points += fold.apply(it)
}
}
return points
}
private sealed interface Fold {
fun filter(p: Point): Boolean
fun apply(p: Point): Point
data class X(private val x: Int) : Fold {
override fun filter(p: Point) = p.x > x
override fun apply(p: Point) = Point(x - (p.x - x), p.y)
}
data class Y(private val y: Int) : Fold {
override fun filter(p: Point) = p.y > y
override fun apply(p: Point) = Point(p.x, y - (p.y - y))
}
}
}
| 0 | Kotlin | 0 | 0 | 08d4a07db82d2b6bac90affb52c639d0857dacd7 | 1,788 | advent-of-kode-2021 | Creative Commons Zero v1.0 Universal |
y2021/src/main/kotlin/adventofcode/y2021/Day23.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2021
import adventofcode.io.AdventSolution
import java.util.PriorityQueue
fun main() {
Day23.solve()
}
object Day23 : AdventSolution(2021, 23, "Amphipods") {
override fun solvePartOne(input: String) = solve(
AmphipodState(
corridor = " ",
rooms = listOf("DB", "AA", "BD", "CC"),
finishedCounts = listOf(2, 2, 2, 2)
)
)
override fun solvePartTwo(input: String) = solve(
AmphipodState(
corridor = " ",
rooms = listOf("DDDB", "ACBA", "BBAD", "CACC"),
finishedCounts = listOf(4, 4, 4, 4)
)
)
private fun solve(initial: AmphipodState): Int? {
val closed = mutableMapOf(initial to 0)
val open = PriorityQueue<AmphipodState>(compareBy { closed.getValue(it) })
open += initial
while (open.isNotEmpty()) {
val candidate = open.poll()
if (candidate.isGoal()) return closed.getValue(candidate)
candidate.tryMoves()
.filter { (newState, cost) -> (closed[newState] ?: Int.MAX_VALUE) > closed.getValue(candidate) + cost }
.forEach { (newState, cost) ->
closed[newState] = closed.getValue(candidate) + cost
open.add(newState)
}
}
return null
}
}
private data class AmphipodState(val corridor: String, val rooms: List<String>, val finishedCounts: List<Int>) {
fun isGoal() = finishedCounts.sum() == 0
fun tryMoves(): List<Pair<AmphipodState, Int>> = listOf(
stepIntoCorridor(0),
stepIntoCorridor(1),
stepIntoCorridor(2),
stepIntoCorridor(3),
stepIntoDestination(0, 'A'),
stepIntoDestination(1, 'B'),
stepIntoDestination(2, 'C'),
stepIntoDestination(3, 'D')
).flatten()
fun stepIntoCorridor(iFromRoom: Int): List<Pair<AmphipodState, Int>> {
if (rooms[iFromRoom].isEmpty()) return emptyList()
val targets = (iFromRoom + 1 downTo 0).takeWhile { corridor[it] == ' ' } + ((iFromRoom + 2)..6).takeWhile { corridor[it] == ' ' }
return targets.map { iPos ->
val symbol = rooms[iFromRoom][0]
val newState = copy(
corridor = corridor.replaceRange(iPos..iPos, symbol.toString()),
rooms = rooms.toMutableList().apply { this[iFromRoom] = rooms[iFromRoom].drop(1) }
)
val cost = rooms[iFromRoom].sumOf(::cost) + cost(symbol) * distances[iFromRoom][iPos]
newState to cost
}
}
fun stepIntoDestination(iToRoom: Int, symbol: Char): List<Pair<AmphipodState, Int>> {
if (rooms[iToRoom].isNotEmpty()) return emptyList()
val sources = listOfNotNull(
(iToRoom + 1 downTo 0).firstOrNull { corridor[it] != ' ' },
((iToRoom + 2)..6).firstOrNull { corridor[it] != ' ' }).filter { corridor[it] == symbol }
return sources.map { iPos ->
val newState = copy(
corridor = corridor.replaceRange(iPos..iPos, " "),
finishedCounts = finishedCounts.toMutableList().apply { this[iToRoom]-- }
)
val cost = cost(symbol) * (finishedCounts[iToRoom] + distances[iToRoom][iPos])
newState to cost
}
}
}
private val distances = listOf(
listOf(2, 1, 1, 3, 5, 7, 8),
listOf(4, 3, 1, 1, 3, 5, 6),
listOf(6, 5, 3, 1, 1, 3, 4),
listOf(8, 7, 5, 3, 1, 1, 2)
)
private fun cost(char: Char) = when (char) {
'A' -> 1
'B' -> 10
'C' -> 100
'D' -> 1000
else -> 0
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 3,636 | advent-of-code | MIT License |
src/main/kotlin/solutions/day20/Day20.kt | Dr-Horv | 112,381,975 | false | null |
package solutions.day20
import solutions.Solver
data class Vector3D(val x: Int, val y: Int, val z: Int)
operator fun Vector3D.plus(v2: Vector3D) = Vector3D(x+v2.x, y+v2.y, z+v2.z)
class Particle(var position: Vector3D, var velocity: Vector3D, val acceleration: Vector3D) {
companion object {
var nbr = 0
fun getIdentity(): Int {
return nbr++
}
}
public val identity = getIdentity()
fun accelerate() {
velocity += acceleration
}
fun move() {
position += velocity
}
}
fun Particle.manhattanDistance(): Int = Math.abs(position.x) + Math.abs(position.y) + Math.abs(position.z)
class Day20: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val particles = input.map(this::parseParticle).toMutableList()
var sortedByDistance = particles.sortedBy(Particle::manhattanDistance)
while (true) {
for (i in (1..10)) {
particles.forEach {
it.accelerate()
it.move()
}
val toRemove = mutableListOf<Particle>()
for (p in particles) {
for (p2 in particles) {
if(p != p2 && p.position == p2.position) {
toRemove.add(p)
toRemove.add(p2)
}
}
}
particles.removeAll(toRemove)
}
val newSortedByDistance = particles.sortedBy(Particle::manhattanDistance)
if(sortedByDistance.map(Particle::identity) == newSortedByDistance.map(Particle::identity)) {
return if(!partTwo) {
sortedByDistance.first().identity.toString()
} else {
particles.size.toString()
}
}
sortedByDistance = newSortedByDistance
}
}
private fun parseParticle(particleDefinition: String): Particle {
println(particleDefinition)
val (position, velocity, acceleration) = particleDefinition.split(", ").map(String::trim)
val p= position.toVector3D()
val v = velocity.toVector3D()
val a = acceleration.toVector3D()
return Particle(p, v, a)
}
}
private fun String.toVector3D(): Vector3D {
val stripped = this.substring(3, this.lastIndex)
val (x,y,z) = stripped.split(",").map(String::trim).map(String::toInt)
return Vector3D(x,y,z)
}
| 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 2,545 | Advent-of-Code-2017 | MIT License |
src/main/kotlin/org/hydev/lcci/lcci_04.kt | VergeDX | 334,298,924 | false | null | package org.hydev.lcci
import kotlin.math.abs
// https://leetcode-cn.com/problems/route-between-nodes-lcci/
fun findWhetherExistsPath(n: Int, graph: Array<IntArray>, start: Int, target: Int): Boolean {
val filteredGraph = graph.distinctBy { (it[0] to it[1]).hashCode() }.toTypedArray()
val nodeEdgeMap = HashMap<Int, HashSet<Int>>()
// Init nodeEdgeMap by using given n, for i in [0, n).
for (i in 0 until n) nodeEdgeMap[i] = HashSet()
// nodeEdgeMap[it[0]] should be exists, because it[0] in range [0, n) too.
graph.forEach { nodeEdgeMap[it[0]]!!.add(it[1]) }
if (start == target) return true
val visitedSet = HashSet<Int>()
// https://oi-wiki.org/graph/dfs/
fun Array<IntArray>.DFS(v: Int) {
visitedSet.add(v)
for (u in nodeEdgeMap[v]!!) {
if (u !in visitedSet) DFS(u)
}
}
filteredGraph.DFS(start)
return target in visitedSet
}
// https://leetcode-cn.com/problems/minimum-height-tree-lcci/
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
companion object {
fun getLayerNodeList(root: TreeNode): List<List<TreeNode>> {
val layerNodeList = ArrayList<List<TreeNode>>().apply { add(listOf(root)) }
while (true) {
val lastGroup = layerNodeList.last()
val allChildList = lastGroup.getAllChildList()
if (allChildList.isEmpty()) break
layerNodeList.add(allChildList)
}
return layerNodeList
}
}
fun sortedArrayToBST(nums: IntArray): TreeNode? {
// https://leetcode-cn.com/problems/minimum-height-tree-lcci/solution/qing-xi-yi-dong-javadi-gui-shi-xian-by-w-i764/
if (nums.isEmpty()) return null
return createMinimalTree(nums, 0, nums.size - 1)
}
// left & right are index of element. (nums is sorted array)
private fun createMinimalTree(nums: IntArray, left: Int, right: Int): TreeNode? {
if (left < 0 || right >= nums.size || left > right) return null
val mid = (left + right) / 2
val n = TreeNode(nums[mid])
n.left = createMinimalTree(nums, left, mid - 1)
n.right = createMinimalTree(nums, mid + 1, right)
return n
}
// https://leetcode-cn.com/problems/list-of-depth-lcci/
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
fun listOfDepth(tree: TreeNode?): Array<ListNode?> {
if (tree == null) return arrayOf()
val layerNodeList = getLayerNodeList(tree)
// Cast TN -> LN, then do link.
val layerTreeNodeList = layerNodeList.map { treeNodeList -> treeNodeList.map { ListNode(it.`val`) } }
layerTreeNodeList.forEach { eachListNodeList ->
eachListNodeList.forEachIndexed { index, listNode ->
val size = eachListNodeList.size
// Last element, default next is null.
if (index == size - 1) return@forEachIndexed
listNode.next = eachListNodeList[index + 1]
}
}
return layerTreeNodeList.map { it[0] }.toTypedArray()
}
}
fun List<TreeNode>.getAllChildList(): List<TreeNode> {
val result = ArrayList<TreeNode>()
this.forEach {
it.left?.let { node -> result.add(node) }
it.right?.let { node -> result.add(node) }
}
return result
}
// https://leetcode-cn.com/problems/check-balance-lcci/
fun isBalancedHelper(root: TreeNode?): Boolean {
if (root == null) return true
val leftChilds =
if (root.left != null) ArrayList<List<TreeNode>>().apply { add(listOf(root.left!!)) } else ArrayList()
val rightChilds =
if (root.right != null) ArrayList<List<TreeNode>>().apply { add(listOf(root.right!!)) } else ArrayList()
while (leftChilds.isNotEmpty()) {
val temp = leftChilds.last().getAllChildList()
if (temp.isEmpty()) break
else leftChilds += temp
}
while (rightChilds.isNotEmpty()) {
val temp = rightChilds.last().getAllChildList()
if (temp.isEmpty()) break
else rightChilds += temp
}
return abs(leftChilds.size - rightChilds.size) <= 1
}
var booleanFlag = true
fun isBalancedRecursion(root: TreeNode?) {
if (root != null && booleanFlag) {
isBalanced(root.left)
isBalanced(root.right)
if (!isBalancedHelper(root)) booleanFlag = false
}
}
fun isBalanced(root: TreeNode?): Boolean {
isBalancedRecursion(root)
return booleanFlag
}
val shouldBeOrder = ArrayList<Int>()
fun isValidBSTHelper(root: TreeNode?) {
if (root != null) {
isValidBSTHelper(root.left)
shouldBeOrder.add(root.`val`)
isValidBSTHelper(root.right)
}
}
// https://leetcode-cn.com/problems/legal-binary-search-tree-lcci/
fun isValidBST(root: TreeNode?): Boolean {
isValidBSTHelper(root)
// After sort, order different x.
// Element duplicate x.
if (shouldBeOrder != shouldBeOrder.sorted() || shouldBeOrder.toSet().size != shouldBeOrder.size) return false
return true
}
// https://leetcode-cn.com/problems/bst-sequences-lcci/
fun BSTSequences(root: TreeNode?): List<List<Int>> {
TODO()
}
// https://leetcode-cn.com/problems/check-subtree-lcci/
fun checkSubTree(t1: TreeNode?, t2: TreeNode?): Boolean {
// https://leetcode-cn.com/problems/check-subtree-lcci/solution/8xing-dai-ma-jie-fa-by-you-yu-ai/
// t2 > t1, because when [null, null], should return true.
if (t2 == null) return true
if (t1 == null) return false
return if (t1.`val` == t2.`val`) checkSubTree(t1.left, t2.left) && checkSubTree(t1.right, t2.right)
else checkSubTree(t1.left, t2) || checkSubTree(t1.right, t2)
}
// https://leetcode-cn.com/problems/paths-with-sum-lcci/
fun pathSum(root: TreeNode?, sum: Int): Int {
TODO()
}
fun main() {
println(
findWhetherExistsPath(
3, arrayOf(
intArrayOf(0, 1), intArrayOf(0, 2),
intArrayOf(1, 2), intArrayOf(1, 2)
), 0, 2
)
)
val debug = TreeNode(1).apply {
left = TreeNode(2).apply {
left = TreeNode(3).apply {
left = TreeNode(4)
}
}
right = TreeNode(2).apply {
right = TreeNode(3).apply {
right = TreeNode(4)
}
}
}
println(isBalanced(debug))
val lcci0405E1 = TreeNode(2).apply {
left = TreeNode(1)
right = TreeNode(3)
}
val lcci0405E2 = TreeNode(5).apply {
left = TreeNode(1)
right = TreeNode(4).apply {
left = TreeNode(3)
right = TreeNode(6)
}
}
// isValidBST(lcci0405E1)
// isValidBST(lcci0405E2)
isValidBSTHelper(lcci0405E2)
println(shouldBeOrder)
// pathSum(lcci0405E2, 0)
}
| 0 | Kotlin | 0 | 0 | 9a26ac2e24b0a0bdf4ec5c491523fe9721c6c406 | 6,873 | LeetCode_Practice | MIT License |
src/main/kotlin/solutions/day18/Day18.kt | Dr-Horv | 570,666,285 | false | {"Kotlin": 115643} | package solutions.day18
import solutions.Solver
import kotlin.math.abs
data class Coordinate3D(val x: Int, val y: Int, val z: Int) {
override fun toString(): String {
return "($x, $y, $z)"
}
}
operator fun Coordinate3D.plus(coordinate: Coordinate3D) =
Coordinate3D(x + coordinate.x, y + coordinate.y, z + coordinate.z)
fun Coordinate3D.manhattanDistance(coordinate: Coordinate3D): Int =
abs(coordinate.x - x) + abs(coordinate.y - y) + abs(coordinate.z - z)
val STEPS = (-2..2).flatMap { x ->
(-2..2).flatMap { y ->
(-2..2).map { z -> Coordinate3D(x, y, z) }
}
}.filter { c -> Coordinate3D(0, 0, 0).manhattanDistance(c) == 1 }
class Day18 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val coordinates = input.map {
val parts = it.split(",").map { c -> c.trim().toInt() }
Coordinate3D(parts[0], parts[1], parts[2])
}.toSet()
if (!partTwo) {
val exposed = coordinates.map {
val neighbours = STEPS.map { step -> it.plus(step) }
.count { c -> coordinates.contains(c) }
6 - neighbours
}
return exposed.sum().toString()
}
val maxX = coordinates.maxOf { it.x } + 1
val maxY = coordinates.maxOf { it.y } + 1
val maxZ = coordinates.maxOf { it.z } + 1
val cube = mutableMapOf<Coordinate3D, Boolean>().withDefault { c ->
when {
c.x in -1..maxX &&
c.y in -1..maxY &&
c.z in -1..maxZ -> true
else -> false
}
}
coordinates.forEach { cube[it] = false }
val emptyCubes = searchBreathFirst(
Coordinate3D(0, 0, 0)
) { n ->
STEPS.map { step -> n.plus(step) }
.filter { c -> cube.getValue(c) }
}
return emptyCubes.flatMap { ec -> STEPS.map { step -> ec.plus(step) }.filter { n -> coordinates.contains(n) } }
.count().toString()
}
fun <Node> searchBreathFirst(
start: Node,
getNeighbours: (n: Node) -> List<Node>
): Set<Node> {
val openSet = mutableListOf(start)
val explored = mutableSetOf(start)
while (openSet.isNotEmpty()) {
val curr = openSet.removeFirst()
for (n in getNeighbours(curr)) {
if (explored.contains(n)) {
continue
}
explored.add(n)
openSet.add(n)
}
}
return explored
}
}
| 0 | Kotlin | 0 | 2 | 6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e | 2,638 | Advent-of-Code-2022 | MIT License |
src/Day03.kt | arisaksen | 573,116,584 | false | {"Kotlin": 42887} | import org.assertj.core.api.Assertions.assertThat
val items: List<Char> = ('a'..'z') + ('A'..'Z')
val priority: List<Int> = (1..26) + (27..52)
val itemPriority: Map<Char, Int> = items.zip(priority).toMap()
typealias Compartment1 = String
typealias Compartment2 = String
typealias Rucksack = Pair<Compartment1, Compartment2>
fun main() {
fun part1(items: List<String>): Int {
val rucksacks: List<Rucksack> =
items.putItemsToRucksackCompartments()
val commonItemsForBothCompartments = rucksacks.map { it.first.filterCharsInCommonWith(it.second) }
val commonItemsSummed = commonItemsForBothCompartments
.flatten()
.sumOf { itemPriority[it] as Int }
return commonItemsSummed
}
fun part2(items: List<String>): Int {
val rucksacks: List<Rucksack> =
items.putItemsToRucksackCompartments()
val rucksacksGrouped = rucksacks
.chunked(3)
/** .also{ log.debug("") } nice for logging */
.map { rucksack -> rucksack.map { it.first + it.second } }
.map { it.filterCommonCharsInListItems() }
val commonItemsSummed = rucksacksGrouped
.flatten()
.sumOf { itemPriority[it] as Int }
return commonItemsSummed
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
assertThat(part1(testInput)).isEqualTo(157)
assertThat(part2(testInput)).isEqualTo(70)
/** "abccddef".toSet() intersect "cadeff".toSet())
* output: [a, c, d, e, f] */
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
fun String.cmp1(): String = this.substring(0, this.length / 2)
fun String.cmp2(): String = this.substring(this.length / 2)
fun List<String>.putItemsToRucksackCompartments(): List<Pair<Compartment1, Compartment2>> =
this.map { it.cmp1() to it.cmp2() }
| 0 | Kotlin | 0 | 0 | 85da7e06b3355f2aa92847280c6cb334578c2463 | 1,983 | aoc-2022-kotlin | Apache License 2.0 |
src/year_2023/day_19/Day19.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2023.day_19
import readInput
data class System(
val workflows: Map<String, Workflow>,
val parts: List<Part>
)
data class Workflow(
val name: String,
val conditions: List<String>
)
data class Part(
val x: Int,
val m: Int,
val a: Int,
val s: Int
)
object Day19 {
/**
*
*/
fun solutionOne(text: List<String>): Int {
val system = parseWorkflows(text)
return system.parts.sumOf { part ->
when (evaluatePart(part, system.workflows)) {
true -> part.x + part.m + part.a + part.s
else -> 0
}
}
}
/**
*
*/
fun solutionTwo(text: List<String>): Int {
return -1
}
private fun parseWorkflows(text: List<String>): System {
val workflowMap = mutableMapOf<String, Workflow>()
val parts = mutableListOf<Part>()
var parsingWorkflows = true
text.forEach { line ->
if (parsingWorkflows) {
if (line.isEmpty()) {
parsingWorkflows = false
} else {
val split = line.split('{')
val name = split[0]
workflowMap[name] = Workflow(
name = name,
conditions = split[1].replace("}", "").split(",")
)
}
} else {
val split = line.replace("{", "").replace("}", "").split(",")
parts.add(
Part(
x = split[0].split("=")[1].toInt(),
m = split[1].split("=")[1].toInt(),
a = split[2].split("=")[1].toInt(),
s = split[3].split("=")[1].toInt(),
)
)
}
}
return System(
workflows = workflowMap,
parts = parts
)
}
private fun evaluatePart(part: Part, workflows: Map<String, Workflow>): Boolean {
var currentWorkflow = "in"
while (currentWorkflow != "A" && currentWorkflow != "R") {
val workflow = workflows[currentWorkflow]!!
currentWorkflow = workflow.conditions.firstNotNullOf { condition ->
evaluateCondition(part, condition)
}
}
return currentWorkflow == "A"
}
private fun evaluateCondition(part: Part, condition: String): String? {
if (!condition.contains(":")) {
// no condition always happen
return condition
}
val split = condition.split(":")
val resultingCondition = split.last()
if (split[0].contains(">")) {
val equationSplit = split[0].split('>')
val value = equationSplit[1].toInt()
val passes = when (equationSplit[0].first()) {
'x' -> part.x > value
'm' -> part.m > value
'a' -> part.a > value
's' -> part.s > value
else -> throw IllegalArgumentException()
}
return when (passes) {
true -> resultingCondition
else -> null
}
} else {
val equationSplit = split[0].split('<')
val value = equationSplit[1].toInt()
val passes = when (equationSplit[0].first()) {
'x' -> part.x < value
'm' -> part.m < value
'a' -> part.a < value
's' -> part.s < value
else -> throw IllegalArgumentException()
}
return when (passes) {
true -> resultingCondition
else -> null
}
}
}
}
fun main() {
val text = readInput("year_2023/day_19/Day19.txt")
val solutionOne = Day19.solutionOne(text)
println("Solution 1: $solutionOne")
val solutionTwo = Day19.solutionTwo(text)
println("Solution 2: $solutionTwo")
}
| 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 4,017 | advent_of_code | Apache License 2.0 |
src/main/kotlin/day12/Day12SubterraneanSustainability.kt | Zordid | 160,908,640 | false | null | package day12
import shared.measureRuntime
import shared.readPuzzle
class Pots(puzzle: List<String>) {
private val initial =
puzzle.first().split(" ")[2] to 0L
private val transforms =
puzzle.filter { it.contains("=>") }.associate { l -> l.split(" ").let { it[0] to it[2] } }
fun solvePart1(): Long {
var p = initial
repeat(20) { p = p.nextGeneration() }
return p.sum()
}
fun solvePart2(): Long {
var leftGenerations = 50000000000L
var prev: Pair<String, Long>
var pots = initial
do {
prev = pots
pots = prev.nextGeneration()
leftGenerations--
} while (pots.first != prev.first)
val drift = pots.second - prev.second
println("Stabilized with $leftGenerations to go!")
println("Drift per generation is $drift.")
pots = pots.first to pots.second + drift * leftGenerations
return pots.sum()
}
fun solveAny(g: Long): Long {
if (g == 0L) return initial.sum()
var leftGenerations = g
val seen = mutableMapOf<String, Pair<Long, Long>>()
var pots = initial
do {
seen[pots.first] = leftGenerations to pots.second
pots = pots.nextGeneration()
leftGenerations--
} while (!seen.contains(pots.first) && leftGenerations > 0)
if (leftGenerations == 0L) return pots.sum()
val before = seen[pots.first]!!
val drift = pots.second - before.second
val loopSize = before.first - leftGenerations
println("Stabilized with $leftGenerations to go!")
println("Drift per generation is $drift and loop size $loopSize.")
val skipLoops = leftGenerations / loopSize
leftGenerations %= loopSize
pots = pots.first to pots.second + drift * skipLoops
println("Skipping $skipLoops loops and finishing $leftGenerations loops..")
repeat(leftGenerations.toInt()) { pots = pots.nextGeneration() }
return pots.sum()
}
private fun Pair<String, Long>.nextGeneration(): Pair<String, Long> {
val (pattern, start) = this
val newPattern = "....$pattern...."
.windowed(5).joinToString("") { transforms.getOrDefault(it, ".") }
val newStart = start - 2 + newPattern.indexOf('#')
return newPattern.trim('.') to newStart
}
private fun Pair<String, Long>.sum() = first.mapIndexed { idx, c -> (idx + second) to c }
.fold(0L) { acc, (idx, c) -> if (c == '#') acc + idx else acc }
}
fun part1(puzzle: List<String>) = Pots(puzzle).solvePart1()
fun part2(puzzle: List<String>) = Pots(puzzle).solvePart2()
fun main() {
val puzzle = readPuzzle(12)
measureRuntime {
println(part1(puzzle))
}
measureRuntime {
println(part2(puzzle))
}
} | 0 | Kotlin | 0 | 0 | f246234df868eabecb25387d75e9df7040fab4f7 | 2,855 | adventofcode-kotlin-2018 | Apache License 2.0 |
src/main/kotlin/Day02.kt | JPQuirmbach | 572,636,904 | false | {"Kotlin": 11093} | fun main() {
fun parseInput(input: String) = input.split("\n")
.flatMap { line ->
line.split(" ")
.zipWithNext()
}
fun part1(input: String): Int {
return parseInput(input)
.map { Pair(toSymbol(it.first), toSymbol(it.second)) }
.sumOf {
val shapeScore = it.second.points
val outcome = calcOutcome(it.second, it.first)
shapeScore + outcome.points
}
}
fun part2(input: String): Int {
return parseInput(input)
.map { Pair(toSymbol(it.first), it.second) }
.sumOf {
val move = determineMove(it.second)
val shapeScore = when (move) {
Result.LOSE -> loseMove(it.first).points
Result.DRAW -> drawMove(it.first).points
Result.WIN -> winMove(it.first).points
}
shapeScore + move.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))
}
fun calcOutcome(player: Symbol, opponent: Symbol): Result {
if (player == opponent) {
return Result.DRAW
}
if (player == Symbol.ROCK && opponent == Symbol.SCISSORS
|| player == Symbol.SCISSORS && opponent == Symbol.PAPER
|| player == Symbol.PAPER && opponent == Symbol.ROCK
) {
return Result.WIN
}
return Result.LOSE
}
fun toSymbol(input: String) = when (input) {
"A", "X" -> Symbol.ROCK
"B", "Y" -> Symbol.PAPER
"C", "Z" -> Symbol.SCISSORS
else -> throw Exception("Invalid")
}
fun winMove(opponent: Symbol) = when (opponent) {
Symbol.ROCK -> Symbol.PAPER
Symbol.PAPER -> Symbol.SCISSORS
Symbol.SCISSORS -> Symbol.ROCK
}
fun drawMove(opponent: Symbol) = opponent
fun loseMove(opponent: Symbol) = when (opponent) {
Symbol.ROCK -> Symbol.SCISSORS
Symbol.PAPER -> Symbol.ROCK
Symbol.SCISSORS -> Symbol.PAPER
}
fun determineMove(player: String) = when (player) {
"X" -> Result.LOSE
"Y" -> Result.DRAW
"Z" -> Result.WIN
else -> throw Exception("Invalid")
}
enum class Symbol(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
}
enum class Result(val points: Int) {
WIN(6),
DRAW(3),
LOSE(0)
}
| 0 | Kotlin | 0 | 0 | 829e11bd08ff7d613280108126fa6b0b61dcb819 | 2,513 | advent-of-code-Kotlin-2022 | Apache License 2.0 |
advent-of-code-2023/src/Day23.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | import lib.graph.Graph
import lib.graph.GraphNode
import lib.graph.GraphNode.Companion.connectToNext
import lib.matrix.*
import lib.matrix.Direction.*
import lib.matrix.Direction.Companion.nextInDirection
private const val DAY = "Day23"
fun main() {
fun testInput() = readInput("${DAY}_test")
fun input() = readInput(DAY)
"Part 1" {
part1(testInput()) shouldBe 94
measureAnswer { part1(input()) }
}
"Part 2" {
part2(testInput()) shouldBe 154
measureAnswer { part2(input()) }
}
}
private fun part1(input: Matrix<Char>) = findLongestPath(input, twoWay = false)
private fun part2(input: Matrix<Char>) = findLongestPath(input, twoWay = true)
private fun findLongestPath(input: Matrix<Char>, twoWay: Boolean): Int {
val graph = buildGraph(input, twoWay)
val endPosition = input.bottomRightPosition.offsetBy(column = -1)
fun longestPath(node: GraphNode<Position>, seen: Set<Position>): Int {
if (node.value == endPosition) return 0
val nextNodes = node.next
.filter { (node, _) -> node.value !in seen }
.ifEmpty { return -1 }
val seenWithThis = seen + node.value
return nextNodes.maxOf { (nextNode, pathToNode) ->
val pathFromNode = longestPath(nextNode, seenWithThis)
if (pathFromNode == -1) -1 else pathToNode + pathFromNode
}
}
return longestPath(graph.roots.single(), emptySet())
}
private fun buildGraph(input: Matrix<Char>, twoWay: Boolean): Graph<Position> {
val graph = Graph<Position>()
val nodesToRoute = ArrayDeque<GraphNode<Position>>()
fun nextNode(position: Position): GraphNode<Position> {
val newNode = position !in graph
return graph.getOrCreate(position).also {
if (newNode) nodesToRoute.addLast(it)
}
}
fun calculateRoutes(node: GraphNode<Position>) {
val queue = ArrayDeque<Pair<Int, Position>>()
val seen = mutableSetOf(node.value)
fun addNextStep(step: Int, position: Position) {
if (position in seen) return
if (input.isNodeAt(position)) {
val nextNode = nextNode(position)
node.connectToNext(nextNode, step)
if (twoWay && !node.isRoot) nextNode.connectToNext(node, step)
} else {
seen += position
queue.addFirst(step to position)
}
}
input.findWays(node.value).forEach { addNextStep(step = 1, it) }
while (queue.isNotEmpty()) {
val (step, position) = queue.removeFirst()
input.findWays(position)
.forEach { addNextStep(step + 1, it) }
}
}
nextNode(Position(row = 0, column = 1))
graph.add(input.bottomRightPosition.offsetBy(column = -1))
while (nodesToRoute.isNotEmpty()) {
calculateRoutes(nodesToRoute.removeFirst())
}
return graph
}
private fun Matrix<Char>.isNodeAt(position: Position): Boolean {
if (position.row == 0 || position.row == lastRowIndex) return true
return position.neighbors().count { this[it] == '#' } < 2
}
private fun Matrix<Char>.findWays(position: Position): List<Position> = buildList {
val matrix = this@findWays
fun checkAndAdd(position: Position, values: String) {
if (position in matrix && matrix[position] in values) add(position)
}
checkAndAdd(position.nextInDirection(UP), ".^")
checkAndAdd(position.nextInDirection(LEFT), ".<")
checkAndAdd(position.nextInDirection(DOWN), ".v")
checkAndAdd(position.nextInDirection(RIGHT), ".>")
}
private fun readInput(name: String) = readMatrix(name)
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 3,677 | advent-of-code | Apache License 2.0 |
src/Day13.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | private sealed class Item : Comparable<Item> {
override fun compareTo(other: Item): Int {
return when {
this is IntItem && other is IntItem -> this.value.compareTo(other.value)
this is ListItem && other is ListItem -> {
val nonEqualItem = this.values.zip(other.values) { l, r -> l.compareTo(r) }.firstOrNull { it != 0 }
nonEqualItem ?: this.values.size.compareTo(other.values.size)
}
else -> {
val left = wrapToListIfNeeded(this)
val right = wrapToListIfNeeded(other)
left.compareTo(right)
}
}
}
private fun wrapToListIfNeeded(item: Item): ListItem =
when (item) {
is ListItem -> item
is IntItem -> ListItem(item)
}
}
private data class IntItem(val value: Int) : Item()
private data class ListItem(val values: List<Item>) : Item() {
constructor(vararg items: Item): this(items.toList())
}
private fun splitList(content: String): List<String> {
if (content.isEmpty()) return emptyList()
val result = mutableListOf<String>()
var depth = 0
var prev = 0
for ((idx, c) in content.withIndex()) {
when (c) {
'[' -> depth++
']' -> depth--
',' -> if (depth == 0) {
result += content.substring(prev, idx)
prev = idx + 1
}
}
}
result += content.substring(prev)
return result
}
private fun parseList(str: String): ListItem {
val content = splitList(str.removeSurrounding("[", "]"))
return ListItem(content.map { parseItem(it) })
}
private fun parseInt(str: String): IntItem = IntItem(str.toInt())
private fun parseItem(str: String): Item =
if (str.startsWith("[") && str.endsWith("]")) {
parseList(str)
} else {
parseInt(str)
}
fun main() {
fun inRightOrder(items: List<ListItem>): Boolean {
val correctOrder = items.sorted()
return items == correctOrder
}
fun parseItems(input: List<String>): List<ListItem> {
return input.mapNotNull { if (it.isNotBlank()) parseList(it) else null }
}
fun part1(input: List<String>): Int {
val items = parseItems(input)
val pairs = items.chunked(size = 2)
val indexesOfSorted = pairs
.withIndex()
.filter { inRightOrder(it.value) }
return indexesOfSorted.sumOf { it.index + 1 }
}
fun part2(input: List<String>): Int {
val items = parseItems(input)
val separators = listOf(
ListItem(ListItem(IntItem(2))),
ListItem(ListItem(IntItem(6))),
)
val sorted = (items + separators).sorted()
val indexesOfSeparators = separators.map { sorted.indexOf(it) }
return indexesOfSeparators.map { it + 1}.reduce(Int::times)
}
// test if implementation meets criteria from the description, like:
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 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 3,192 | aoc2022 | Apache License 2.0 |
02friendsinneed/src/Main.kt | Minkov | 125,619,391 | false | null | import java.util.*
import kotlin.math.min
fun fakeInput() {
val test = """3 2 1
1
1 2 1
3 2 2
5 8 2
1 2
1 2 5
4 1 2
1 3 1
3 4 4
4 5 1
2 4 3
5 2 1
2 3 20"""
val stream = test.byteInputStream()
System.setIn(stream)
}
fun main(args: Array<String>) {
// fakeInput()
// println(solve())
// println("-".repeat(15))
println(solve())
}
class Node(var name: Int, var distance: Int) {
override fun toString(): String {
return "(${this.name} ${this.distance})"
}
}
fun solve(): Int {
val (n, m, _) = readLine()!!.split(" ").map { it.toInt() }
val hospitals = readLine()!!.split(" ").map { it.toInt() }.toSet()
val nodes = Array(n + 1) { mutableListOf<Node>() }
for (i in 0 until m) {
val (x, y, d) = readLine()!!.split(" ").map { it.toInt() }
nodes[x].add(Node(y, d))
nodes[y].add(Node(x, d))
}
var best = 1 shl 20
hospitals
.asSequence()
.map { getDistancesFrom(it, nodes) }
.map { distances ->
distances.indices
.filterNot { hospitals.contains(it).or(it == 0) }
.sumBy { distances[it] }
}
.forEach { best = min(best, it) }
return best
}
fun getDistancesFrom(startNode: Int, nodes: Array<MutableList<Node>>): Array<Int> {
val infinity = 1 shl 20
val used = mutableSetOf<Int>()
val queue = TreeSet<Node>(kotlin.Comparator { x, y -> x.distance.compareTo(y.distance) })
val distances = Array(nodes.size) { infinity }
distances[startNode] = 0
queue.add(Node(startNode, 0))
while (!queue.isEmpty()) {
val node = queue.first()
queue.remove(node)
if (used.contains(node.name)) {
continue
}
used.add(node.name)
nodes[node.name]
.forEach { next ->
if (distances[next.name] > distances[node.name] + next.distance) {
distances[next.name] = distances[node.name] + next.distance
queue.add(Node(next.name, distances[next.name]))
}
}
}
return distances
}
| 0 | JavaScript | 4 | 1 | 3c17dcadd5aa201166d4fff69d055d7ec0385018 | 2,183 | judge-solved | MIT License |
src/Day08.kt | mvmlisb | 572,859,923 | false | {"Kotlin": 14994} | private inline fun processInnerRow(rows: List<List<Int>>, process: (rowIndex: Int, row: List<Int>, indexInRow: Int) -> Unit) {
rows.forEachIndexed { rowIndex, row ->
val isOuterRowIndex = rowIndex == 0 || rowIndex == rows.lastIndex
if (!isOuterRowIndex)
row.indices.forEach { indexInRow ->
val isOuterIndexInRow = indexInRow == 0 || indexInRow == row.lastIndex
if (!isOuterIndexInRow) process(rowIndex, row, indexInRow)
}
}
}
private inline fun <T> processUpDown(
rowIndex: Int,
indexInRow: Int,
rows: List<List<Int>>,
process: (up: List<Int>, bottom: List<Int>, number: Int) -> T
): T {
val number = rows[rowIndex][indexInRow]
val up = (0 until rowIndex).map { rows[it][indexInRow] }.reversed()
val bottom = (rowIndex + 1 until rows.size).map { rows[it][indexInRow] }
return process(up, bottom, number)
}
private inline fun <T> processLeftRight(
indexInRow: Int,
row: List<Int>,
process: (left: List<Int>, right: List<Int>, number: Int) -> T
): T {
val number = row[indexInRow]
val left = row.subList(0, indexInRow).reversed()
val right = row.subList(indexInRow + 1, row.size)
return process(left, right, number)
}
private fun List<Int>.incrementUntilReceiveEqualOrGreaterNumber(numberInclusive: Int): Int {
var count = 0
for (number in this) {
count += 1
if (number >= numberInclusive)
break
}
return count
}
private fun part1(rows: List<List<Int>>): Int {
val outerVisibleTrees = ((rows.size + rows.first().size) * 2) - 4
var innerVisibleTrees = 0
processInnerRow(rows) { rowIndex, row, indexInRow ->
if (processUpDown(
rowIndex,
indexInRow,
rows
) { up: List<Int>, bottom: List<Int>, number: Int -> up.none { it >= number } || bottom.none { it >= number } } || processLeftRight(
indexInRow,
row
) { left, right, number -> left.none { it >= number } || right.none { it >= number } }
)
innerVisibleTrees++
}
return innerVisibleTrees + outerVisibleTrees
}
private fun part2(rows: List<List<Int>>) = buildSet {
processInnerRow(rows) { rowIndex, row, indexInRow ->
add(processUpDown(rowIndex, indexInRow, rows) { up, bottom, number ->
up.incrementUntilReceiveEqualOrGreaterNumber(number) * bottom.incrementUntilReceiveEqualOrGreaterNumber(number)
} * processLeftRight(indexInRow, row) { left, right, number ->
left.incrementUntilReceiveEqualOrGreaterNumber(number) * right.incrementUntilReceiveEqualOrGreaterNumber(number)
})
}
}.max()
fun main() {
val input = readInput("Day08_test")
val rows = input
.map { line -> line.toCharArray() }
.map { charArray -> charArray.map { char -> char.toString().toInt() } }
println(part1(rows))
println(part2(rows))
}
| 0 | Kotlin | 0 | 0 | 648d594ec0d3b2e41a435b4473b6e6eb26e81833 | 2,991 | advent_of_code_2022 | Apache License 2.0 |
src/Day04.kt | razvn | 573,166,955 | false | {"Kotlin": 27208} |
fun main() {
val day = "Day04"
fun part1(input: List<String>): Int {
val pairs = parse(input)
val including = pairs.filter { rangeContains(it.first, it.second)}
return including.size
}
fun part2(input: List<String>): Int {
val pairs = parse(input)
val including = pairs.filter { rangeOverlap(it.first, it.second)}
return including.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
// println(part1(testInput))
// println(part2(testInput))
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
private fun parse(input: List<String>): List<Pair<IntRange, IntRange>> = input.map { line ->
val (elf1String, elf2String) = line.split(",")
val elf1 = elf1String.split("-").map { it.toInt() }.let { IntRange(it.first(), it.last())}
val elf2 = elf2String.split("-").map { it.toInt() }.let { IntRange(it.first(), it.last())}
elf1 to elf2
}
private fun rangeContains(one: IntRange, other: IntRange): Boolean {
return (one.first in other && one.last in other)
|| (other.first in one && other.last in one)
}
private fun rangeOverlap(one: IntRange, other: IntRange): Boolean {
return (one.first in other || one.last in other)
|| (other.first in one || other.last in one)
}
| 0 | Kotlin | 0 | 0 | 73d1117b49111e5044273767a120142b5797a67b | 1,456 | aoc-2022-kotlin | Apache License 2.0 |
2022/src/main/kotlin/Day12.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day12 {
fun part1(input: String): Int {
val map = input.splitNewlines()
val start = findChar(map, 'S')[0]
val end = findChar(map, 'E')[0]
return shortestPath(map, start, end)!!.size - 1
}
fun part2(input: String): Int {
val map = input.splitNewlines()
val starts = findChar(map, 'a')
val end = findChar(map, 'E')[0]
return starts.minOfOrNull { start -> shortestPath(map, start, end)?.size ?: Int.MAX_VALUE }!! - 1
}
private fun shortestPath(map: List<String>, start: Pos, end: Pos): List<Pos>? {
val queue = mutableListOf(listOf(start))
val explored = mutableSetOf(start)
while (queue.isNotEmpty()) {
val path = queue.removeFirst()
val pos = path.last()
if (pos == end) {
return path
}
findValidMoves(map, explored, pos)
.forEach {
queue.add(path + it)
explored.add(it)
}
}
return null
}
private fun findValidMoves(map: List<String>, explored: Set<Pos>, pos: Pos): List<Pos> {
return pos
.adjacent
.filter { next ->
inBounds(map, next)
&& next !in explored
&& canMove(map[pos.y][pos.x], map[next.y][next.x])
}
}
private fun inBounds(map: List<String>, pos: Pos) = pos.x in map[0].indices && pos.y in map.indices
private fun canMove(from: Char, to: Char) = to.height - from.height <= 1
private val Char.height: Int
get() = when {
this == 'S' -> 'a'.code
this == 'E' -> 'z'.code
else -> this.code
}
private fun findChar(map: List<String>, char: Char): List<Pos> {
val found = mutableListOf<Pos>()
map.indices.forEach { y ->
map[y].indices.forEach { x ->
if (map[y][x] == char) {
found.add(Pos(x, y))
}
}
}
return found
}
private data class Pos(val x: Int, val y: Int) {
val adjacent: List<Pos>
get() = listOf(
Pos(x + 1, y),
Pos(x - 1, y),
Pos(x, y + 1),
Pos(x, y - 1)
)
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 2,031 | advent-of-code | MIT License |
src/Day08.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | fun main() {
fun decode(notes: List<String>): HashMap<Char, Char> {
val segMap = HashMap<Char, Char>()
val segCount = HashMap<Char, Int>()
val decodeDigMap = HashMap<Int, String>()
segCount['a'] = 0
segCount['b'] = 0
segCount['c'] = 0
segCount['d'] = 0
segCount['e'] = 0
segCount['f'] = 0
segCount['g'] = 0
notes.sortedBy { it.length }.forEach {
when (it.length) {
2 -> decodeDigMap[1] = it
3 -> decodeDigMap[7] = it
4 -> decodeDigMap[4] = it
7 -> decodeDigMap[8] = it
}
it.forEach { c -> segCount[c] = segCount[c]!! + 1 }
}
segMap['a'] = decodeDigMap[7]!!.filter { !decodeDigMap[1]!!.contains(it) }.chars().findAny().asInt.toChar()
segMap['b'] = segCount.filterValues { it == 6 }.keys.first()
segMap['c'] = segCount.filterValues { it == 8 }.filterKeys { it != segMap['a']!! }.keys.first()
segMap['d'] = segCount.filterValues { it == 7 }.filterKeys { decodeDigMap[4]!!.contains(it) }.keys.first()
segMap['e'] = segCount.filterValues { it == 4 }.keys.first()
segMap['f'] = segCount.filterValues { it == 9 }.keys.first()
segMap['g'] = segCount.filterValues { it == 7 }.filterKeys { it != segMap['d']!! }.keys.first()
return segMap.entries.associate { (k, v) -> v to k } as HashMap<Char, Char>
}
fun part1(input: List<Pair<List<String>, List<String>>>): Int {
return input.map { r ->
val notes = r.first
val inp = r.second
val digMap = HashMap<String, Int>()
digMap["abcefg"] = 0
digMap["cf"] = 1
digMap["acdeg"] = 2
digMap["acdfg"] = 3
digMap["bcdf"] = 4
digMap["abdfg"] = 5
digMap["abdefg"] = 6
digMap["acf"] = 7
digMap["abcdefg"] = 8
digMap["abcdfg"] = 9
val decodedSegMap = decode(notes)
val tmp =
inp.map { it.chars().toArray().map { c -> decodedSegMap[c.toChar()]!! }.sorted().joinToString("") }
.toList()
tmp.map { digMap[it]!! }.count { listOf(1, 4, 7, 8).contains(it) }
}.sum()
}
fun part2(input: List<Pair<List<String>, List<String>>>): Int {
return input.map { r ->
val notes = r.first
val inp = r.second
val digMap = HashMap<String, Int>()
digMap["abcefg"] = 0
digMap["cf"] = 1
digMap["acdeg"] = 2
digMap["acdfg"] = 3
digMap["bcdf"] = 4
digMap["abdfg"] = 5
digMap["abdefg"] = 6
digMap["acf"] = 7
digMap["abcdefg"] = 8
digMap["abcdfg"] = 9
val decodedSegMap = decode(notes)
val tmp = inp.map {
it.chars().toArray().map { c -> decodedSegMap[c.toChar()]!! }.sorted().joinToString("")
}//.toList()
.map { digMap[it]!!.toString() }
tmp.joinToString("").toInt()
}.sum()
}
fun preprocessing(input: String): List<Pair<List<String>, List<String>>> {
return input.trim().split("\r\n").map { r ->
val tmp = r.trim().split(" | ").map { it.split(" ") }
Pair(tmp[0], tmp[1])
}.toList()
}
val realInp = read_testInput("real8")
val testInp = read_testInput("test8")
// val testInp = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
// println("Test 1: ${part1(preprocessing(testInp))}")
// println("Real 1: ${part1(preprocessing(realInp))}")
// println("-----------")
println("Test 2: ${part2(preprocessing(testInp))}")
println("Real 2: ${part2(preprocessing(realInp))}")
}
| 0 | Kotlin | 0 | 0 | 3e33ab078f8f5413fa659ec6c169cd2f99d0b374 | 3,880 | advent_of_code21_kotlin | Apache License 2.0 |
src/main/Day14.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day14
import geometry.*
import utils.readInput
private val source: Position = 500 to 0
class Cave(private val rocks: Set<Position>) {
private val filled = rocks.toMutableSet()
private val depth = rocks.maxOf(Position::y)
fun fill(): Int =
generateSequence { drop() }.takeWhile { it == Drop.SETTLES && source !in filled }.count() +
if (source in filled) 1 else 0
fun visualize(): String = buildString {
for (y in 0..depth) {
for (x in -depth..depth) {
append(
when (source.x + x to y) {
source -> '+'
in rocks -> '#'
in filled -> 'o'
else -> '.'
}
)
}
append("\n")
}
}
private enum class Drop {
SETTLES,
KEEPS_FALLING
}
private fun drop(): Drop {
var position = source
while (position.y <= depth) {
val down = position.move(Direction.Up)
val next =
listOf(down, down.move(Direction.Left), down.move(Direction.Right)).firstOrNull {
it !in filled
}
if (next == null) {
filled.add(position)
return Drop.SETTLES
}
position = next
}
return Drop.KEEPS_FALLING
}
}
fun List<String>.readCave(): Cave = readRocks().let(::Cave)
fun List<String>.readRocks() = map(String::toRocks).reduce(Set<Position>::union)
fun String.toRocks(): Set<Position> =
split(" -> ".toRegex())
.map(String::toPosition)
.windowed(2)
.flatMap { (a, b) -> a.straightLineTo(b) }
.toSet()
fun String.toPosition(): Position = split(",").map(String::toInt).let { (x, y) -> x to y }
fun Position.straightLineTo(other: Position): List<Position> =
when {
x == other.x -> (y towards other.y).map { x to it }
y == other.y -> (x towards other.x).map { it to y }
else -> error("No straight line from $this to $other")
}
private infix fun Int.towards(end: Int) =
when {
this <= end -> this..end
else -> (end..this).reversed()
}
private const val filename = "Day14"
fun part1(filename: String): Int {
val cave = readInput(filename).readCave()
return cave.fill()
}
fun part2(filename: String): Int {
val lines = readInput(filename)
val cave = lines.readCaveWithFloor()
return cave.fill()
}
fun List<String>.readCaveWithFloor(): Cave {
val rocks = readRocks()
val depth = rocks.maxOf { it.y } + 2
return Cave(rocks + (-depth..depth).map { it + source.x to depth }.toSet())
}
fun main() {
println(part1(filename))
println(part2(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 2,814 | aoc-2022 | Apache License 2.0 |
src/day2/Day02.kt | kongminghan | 573,466,303 | false | {"Kotlin": 7118} | package day2
import readInput
import java.lang.IllegalArgumentException
const val wonScore = 6
const val drawScore = 3
enum class Move(val score: Int) {
Rock(1),
Paper(2),
Scissors(3)
}
data class Play(
val letter: String,
val move: Move
)
fun main() {
val winPairs = mapOf(
Move.Rock to Move.Paper,
Move.Paper to Move.Scissors,
Move.Scissors to Move.Rock
)
val loseMap = mapOf(
Move.Rock to Move.Scissors,
Move.Paper to Move.Rock,
Move.Scissors to Move.Paper
)
val moveMap = mapOf(
"A" to Move.Rock,
"X" to Move.Rock,
"B" to Move.Paper,
"Y" to Move.Paper,
"C" to Move.Scissors,
"Z" to Move.Scissors,
)
val Lose = "X"
val Draw = "Y"
val Win = "Z"
fun List<String>.sumOfGame(transform: (Pair<Play, Play>) -> Int) = this.sumOf {
val game = it.split(" ")
val opponent = game.first()
val me = game.last()
transform(
Play(opponent, moveMap[opponent]!!) to Play(me, moveMap[me]!!)
)
}
fun totalScore(input: List<String>): Int {
return input.sumOfGame { pair ->
pair.second.move.score + if (winPairs[pair.first.move] == pair.second.move) {
wonScore
} else if (pair.first.move.score == pair.second.move.score) {
drawScore
} else {
0
}
}
}
fun totalScoreWithoutGamePlay(input: List<String>): Int {
return input.sumOfGame {
when (it.second.letter) {
Lose -> loseMap[it.first.move]!!.score
Win -> winPairs[it.first.move]!!.score + wonScore
Draw -> it.first.move.score + drawScore
else -> throw IllegalArgumentException()
}
}
}
fun part1(input: List<String>): Int {
return totalScore(input = input)
}
fun part2(input: List<String>): Int {
return totalScoreWithoutGamePlay(input = input)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(day = 2, name = "Day02_test")
check(part1(testInput) == 19)
check(part2(testInput) == 16)
val input = readInput(day = 2, name = "Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f602900209712090778c161d407ded8c013ae581 | 2,374 | advent-of-code-kotlin | Apache License 2.0 |
src/Day08.kt | purdyk | 572,817,231 | false | {"Kotlin": 19066} |
fun <T> List<List<T>>.column(y: Int): List<T> {
return (0 .. this.lastIndex).map { this[it][y] }
}
fun main() {
fun part1(input: List<List<Int>>): String {
val max = input.lastIndex
var visible = (max * 4)
(1 until max).forEach { x ->
(1 until max).forEach { y ->
val dirs = sequence {
// right
yield(input[x].drop(y + 1))
// left
yield(input[x].take(y))
// up
yield(input.column(y).take(x))
// down
yield(input.column(y).drop(x + 1))
}
val thisTree = input[x][y]
if (dirs.any { it.all { t -> t < thisTree } }) {
visible += 1
} else {
// print("Not visible: $x, $y == $thisTree\n")
}
}
}
return visible.toString()
}
fun part2(input: List<List<Int>>): String {
val max = input.lastIndex
val scores = (0 .. max).flatMap { x ->
(0 .. max).map { y ->
val dirs = sequence {
// right
yield(input[x].drop(y + 1))
// left
yield(input[x].take(y).reversed())
// up
yield(input.column(y).take(x).reversed())
// down
yield(input.column(y).drop(x + 1))
}
val thisTree = input[x][y]
dirs.map { (it.indexOfFirst { t -> t >= thisTree }.takeIf { it > -1 } ?: it.lastIndex) + 1 }
.reduce { acc, i -> acc * i }
}
}
// print(scores)
return scores.max().toString()
}
val day = "08"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test").split("\n").map { it.map { it.toString().toInt() } }
println("Test: ")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == "21")
check(part2(testInput) == "8")
val input = readInput("Day${day}").split("\n").map { it.map { it.toString().toInt() } }
println("\nProblem: ")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 02ac9118326b1deec7dcfbcc59db8c268d9df096 | 2,369 | aoc2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2021/day08/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2021.day08
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
println(part1())
println(part2())
}
fun part1(): Int {
readInput(2021, 8).useLines { lines ->
val knownLengths = listOf(2, 3, 4, 7)
return lines
.map { it.substringAfterLast("| ") }
.map { it.split(" ") }
.sumOf { it.count { digit -> digit.length in knownLengths } }
}
}
fun part2(): Int {
var result = 0
readInput(2021, 8).forEachLine { line ->
val (numberString, puzzleString) = line.split(" | ")
val numbers = numberString.split(" ").map { it.toSet() }
val decodedList = arrayOfNulls<Set<Char>>(10)
val decodedMap = hashMapOf<Set<Char>, Int>()
val other = arrayListOf<Set<Char>>()
for (number in numbers) {
val value = when (number.size) {
7 -> 8
4 -> 4
3 -> 7
2 -> 1
else -> { other.add(number); continue }
}
decodedMap[number] = value
decodedList[value] = number
}
for (number in other) {
val value = when (number.size) {
5 -> when {
number.intersect(decodedList[4]!!).size == 2 -> 2
number.containsAll(decodedList[1]!!) -> 3
else -> 5
}
else -> when {
number.containsAll(decodedList[4]!!) -> 9
!number.containsAll(decodedList[1]!!) -> 6
else -> 0
}
}
decodedMap[number] = value
decodedList[value] = number
}
result += puzzleString.split(" ").map { it.toSet() }.fold(0) { acc, s -> acc * 10 + decodedMap.getValue(s) }
}
return result
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,885 | adventofcode | Apache License 2.0 |
leetcode2/src/leetcode/maximum-product-subarray.kt | hewking | 68,515,222 | false | null | /**
* 152. 乘积最大子序列
* https://leetcode-cn.com/problems/maximum-product-subarray/
* 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
object MaximumProductSubarray {
class Solution {
var res = 0
/**
* 思路:回溯法 最简单暴力解答,超出时间限制
*/
fun maxProduct_(nums: IntArray): Int {
res = nums.reduce({ pre, cur ->
Math.min(pre, cur)
})
backTrack(nums, 0)
return res
}
fun backTrack(nums: IntArray, start: Int) {
if (start >= nums.size) {
return
}
for (i in start until nums.size) {
val subArr = nums.copyOfRange(start, i + 1)
val minusRes = minusInArray(subArr)
res = Math.max(res, minusRes)
backTrack(nums, i + 1)
}
}
/**
* 获取数组的乘积
*/
fun minusInArray(nums: IntArray): Int {
return nums.reduce { acc, i ->
acc * i
}
}
/**
* https://leetcode-cn.com/problems/maximum-product-subarray/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--36/
*/
fun maxProduct(nums: IntArray): Int {
if (nums.isEmpty()) return 0
val n = nums.size
val dpMax = IntArray(n)
dpMax[0] = nums[0]
val dpMin = IntArray(n)
dpMin[0] = nums[0]
var max = nums[0]
for (i in 1 until n) {
dpMax[i] = Math.max(dpMin[i - 1] * nums[i] , Math.max(dpMax[i - 1] * nums[i],nums[i]))
dpMin[i] = Math.min(dpMin[i - 1] * nums[i] ,Math.min(dpMax[i - 1] * nums[1] ,nums[i]))
max = Math.max(max,dpMax[i])
}
return max
}
}
}
| 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,364 | leetcode | MIT License |
src/Day05.kt | buczebar | 572,864,830 | false | {"Kotlin": 39213} | typealias Stack = List<Char>
fun main() {
fun solve(input: Pair<MutableList<Stack>, List<StackMove>>, inputModifier: (List<Char>) -> List<Char>): String {
val (stacks, moves) = input
moves.forEach { move ->
stacks[move.to] = stacks[move.from].take(move.amount).let { inputModifier.invoke(it) } + stacks[move.to]
stacks[move.from] = stacks[move.from].drop(move.amount)
}
return stacks.filter { it.isNotEmpty() }.map { it.first() }.joinToString("")
}
fun part1(input: Pair<MutableList<Stack>, List<StackMove>>) = solve(input) { it.reversed() }
fun part2(input: Pair<MutableList<Stack>, List<StackMove>>) = solve(input) { it }
check(part1(parseInput("Day05_test")) == "CMZ")
check(part2(parseInput("Day05_test")) == "MCD")
println(part1(parseInput("Day05")))
println(part2(parseInput("Day05")))
}
private fun parseInput(name: String): Pair<MutableList<Stack>, List<StackMove>> {
fun parseStacks(inputString: String): MutableList<Stack> {
val stackValues = inputString.lines().dropLast(1)
.map { line ->
line.replace(" ", "[-]")
.remove("[^\\w-]".toRegex())
.toList()
}
.transpose()
.map { stack -> stack.filter { it != '-' }.toMutableList() }
return stackValues.toMutableList()
}
fun parseMoves(inputString: String): List<StackMove> {
val lineRegex = "(\\d+)".toRegex()
return inputString.lines()
.map { line -> lineRegex.findAll(line).map { it.value.toInt() }.toList() }
.map { (amount, from, to) -> StackMove(amount, from - 1, to - 1) }
}
val (stacks, moves) = readGroupedInput(name)
return Pair(parseStacks(stacks), parseMoves(moves))
}
private data class StackMove(
val amount: Int,
val from: Int,
val to: Int
)
| 0 | Kotlin | 0 | 0 | cdb6fe3996ab8216e7a005e766490a2181cd4101 | 1,912 | advent-of-code | Apache License 2.0 |
src/main/kotlin/aoc2023/Day05.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import kotlinx.coroutines.*
import utils.InputUtils
import kotlin.math.max
import kotlin.math.min
enum class Mode {
PARALLEL, BRUTE, SPLIT
}
val mode = Mode.SPLIT
data class SeedRange(val destStart: Long, val sourceStart: Long, val size: Int) {
fun contains(x: Long) = (x >= sourceStart) && (x < (sourceStart + size))
fun endInclusive() = sourceStart + size - 1
fun endExclusive() = sourceStart + size
fun apply(x: Long) = if (contains(x)) { x + offset() } else { x }
fun offset() = destStart - sourceStart
fun applyAndSplit(range: LongRange): List<LongRange> = if (intersect(range)) {
if (range.contains(sourceStart) && range.contains(endInclusive())) {
listOf(destStart..< (destStart + size))
} else { emptyList() }
} else { emptyList() }
fun intersect(range: LongRange): Boolean = (sourceStart <= range.last) xor (endInclusive() <= range.first)
}
data class SeedMap(val from: String, val to: String, val ranges: List<SeedRange>) {
val sortedRanges = ranges.sortedBy { it.sourceStart }
fun apply(x: Long) = rangeFor(x)?.apply(x) ?: x
private fun rangeFor(x: Long) = ranges.firstOrNull { it.contains(x) }
fun apply(range: LongRange): Sequence<LongRange> = sequence {
var current = range.first
val splits = sortedRanges.filter { it.intersect(range) }
splits.forEach { split ->
if (split.sourceStart > current) { yield(current..<split.sourceStart) }
val start = max(split.sourceStart, current)
val end = min(split.endInclusive(), range.endInclusive)
val offset = split.offset()
yield((start+offset)..(end+offset))
current = end
}
if (current < range.endInclusive) {
yield(current..range.endInclusive)
}
}
}
data class Day5(val seeds: List<Long>, val maps: List<SeedMap>) {
fun mapSeed(seed: Long) = maps.fold(seed) { acc, map -> map.apply(acc)}
fun minOfRange(range: LongRange) = maps.fold(listOf(range)) { acc, map -> acc.flatMap { map.apply(it) }}
.minOf { it.start }
}
fun String.listOfLongs(): List<Long> = trim().split("\\D+".toRegex()).map { it.trim().toLong() }
fun main() {
val testInput = """seeds: 79 14 55 13
seed-to-soil map:
50 98 2
52 50 48
soil-to-fertilizer map:
0 15 37
37 52 2
39 0 15
fertilizer-to-water map:
49 53 8
0 11 42
42 0 7
57 7 4
water-to-light map:
88 18 7
18 25 70
light-to-temperature map:
45 77 23
81 45 19
68 64 13
temperature-to-humidity map:
0 69 1
1 0 69
humidity-to-location map:
60 56 37
56 93 4""".trimIndent().split("\n")
val titleParser = "(\\w+)-to-(\\w+) map:".toRegex()
fun <T> Iterable<T>.tail() = drop(1)
fun List<String>.parseSeedMap(): SeedMap {
val (from, to) = titleParser.matchEntire(first())!!.destructured
val ranges = tail().map {
val (dest, source, size) = it.listOfLongs()
SeedRange(dest, source, size.toInt())
}
return SeedMap(from, to, ranges)
}
fun List<String>.parseDay5(): Day5 {
val blocks = toBlocksOfLines()
val seeds =
blocks.first().first().substringAfter(":").listOfLongs()
return Day5(seeds, blocks.drop(1).map { it.parseSeedMap()})
}
fun part1(input: List<String>): Long {
val problem = input.parseDay5()
return problem.seeds.minOf { problem.mapSeed(it) }
}
fun LongRange.chunked(size: Long) = sequence {
var current = first
while(current <= last) {
val end = kotlin.math.min(current + size, last + 1)
yield(current ..< end)
current = end
}
}
fun part2(input: List<String>): Long {
val problem = input.parseDay5()
val seedRanges = problem.seeds.chunked(2).map { it[0]..<(it[0] + it[1]) }
val totalSize = problem.seeds.chunked(2).sumOf { it[1] }
println("Total size: $totalSize")
return when(mode) {
Mode.PARALLEL ->
seedRanges.asSequence().map { range ->
runBlocking(Dispatchers.IO) {
val min = range.chunked(5_000_000).toList()
.pmap { subRange -> subRange.minOf { problem.mapSeed(it) }}
.min()
println("Min: $min")
min
}}
.min()
Mode.BRUTE -> {
var complete = 0L
seedRanges
.onEach { complete += (1 + it.last - it.first) }
.map { range -> range.minOf { problem.mapSeed(it) } }
.onEach { println("Min: $it, $complete/$totalSize") }
.min()
}
Mode.SPLIT -> {
seedRanges.minOf { range -> problem.minOfRange(range) }
} }
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 35L)
println(part2(testInput))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 5)
val input = puzzleInput.toList()
println(part1(input))
val start = System.currentTimeMillis()
println(part2(input))
println(System.currentTimeMillis() - start)
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 5,314 | aoc-2022-kotlin | Apache License 2.0 |
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/SlidingWindow.kt | betulnecanli | 568,477,911 | false | {"Kotlin": 167849} | /*
Sliding window is a technique used for efficiently processing arrays or lists by maintaining a "window" of elements as
you iterate through the data.
This can be particularly useful for problems where you need to find a subarray,
substring, or some other contiguous segment of the data that satisfies a certain condition.
*/
// "Find the maximum sum of a subarray of a fixed size K."
fun maxSumSubarray(arr: IntArray, k: Int): Int {
var windowSum = 0
var maxSum = 0
// Calculate the initial sum of the first window of size K
for (i in 0 until k) {
windowSum += arr[i]
}
// Iterate through the array, moving the window by one element at a time
for (i in k until arr.size) {
// Add the current element to the window sum and subtract the first element of the previous window
windowSum = windowSum + arr[i] - arr[i - k]
// Update the maximum sum if the current window sum is greater
maxSum = maxOf(maxSum, windowSum)
}
return maxSum
}
fun main() {
val arr = intArrayOf(1, 4, 2, 10, 2, 3, 1, 0, 20)
val k = 3
val result = maxSumSubarray(arr, k)
println("Maximum sum of a subarray of size $k is: $result")
}
/*
The "Fruits into Baskets" problem is a classic sliding window problem where you are given an array of fruits,
and you need to find the length of the longest subarray with at most two distinct fruit types.
Here's a Kotlin implementation using the sliding window pattern:
*/
fun totalFruit(tree: IntArray): Int {
var maxFruits = 0
var fruitCount = 0
var left = 0
val fruitFrequency = mutableMapOf<Int, Int>()
for (right in tree.indices) {
// Add the current fruit to the frequency map
fruitFrequency[tree[right]] = fruitFrequency.getOrDefault(tree[right], 0) + 1
// Increment fruit count
fruitCount++
// Adjust the window by removing fruits until only two distinct fruits are in the basket
while (fruitFrequency.size > 2) {
fruitFrequency[tree[left]] = fruitFrequency[tree[left]]!! - 1
if (fruitFrequency[tree[left]] == 0) {
fruitFrequency.remove(tree[left])
}
left++
fruitCount--
}
// Update the maximum number of fruits
maxFruits = maxOf(maxFruits, fruitCount)
}
return maxFruits
}
fun main() {
val tree = intArrayOf(1, 2, 1, 3, 4, 3, 5, 1, 2)
val result = totalFruit(tree)
println("The length of the longest subarray with at most two distinct fruits is: $result")
}
/*
In this example, the totalFruit function takes an array tree representing different types of fruits.
The goal is to find the length of the longest subarray with at most two distinct fruit types.
The function uses a sliding window approach to keep track of the frequency of fruits in the basket.
The fruitFrequency map is used to store the count of each fruit type in the current window.
The left pointer is adjusted to maintain at most two distinct fruit types in the basket.
The fruitCount variable keeps track of the length of the current subarray.
*/
| 2 | Kotlin | 2 | 40 | 70a4a311f0c57928a32d7b4d795f98db3bdbeb02 | 3,133 | Kotlin-Data-Structures-Algorithms | Apache License 2.0 |
kotlin/src/main/kotlin/year2023/Day21.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
fun main() {
val input = readInput("Day21")
Day21.part1(input).println()
Day21.part2(input).println()
}
object Day21 {
fun part1(input: List<String>): Int {
return input.gardenPlotsReached(64)
}
fun part2(input: List<String>): Long {
println("f(x) = a*x^2 + b*x + c = 0")
val x0 = 65
val a0 = input.gardenPlotsReached(x0)
println("f(0) = gardenPlotsReached(65 + 131*0) = gardenPlotsReached($x0) = $a0")
val x1 = 65 + 131
val a1 = input.gardenPlotsReached(x1)
println("f(1) = gardenPlotsReached(65 + 131*1) = gardenPlotsReached($x1) = $a1")
val x2 = 65 + (131 * 2)
val a2 = input.gardenPlotsReached(x2)
println("f(2) = gardenPlotsReached(65 + 131*2) = gardenPlotsReached($x2) = $a2")
val steps = 26501365L
val cycles = steps / 131
val solution = ((a2 - a1) - (a1 - a0)) * (cycles * (cycles - 1) / 2) + (a1 - a0) * cycles + a0
println("gardenPlotsReached($steps) = gardenPlotsReached(65 + 131*$cycles) = f($cycles)")
println("f($cycles) = (($a2-$a1)-($a1-$a0))*$cycles*($cycles-1)/2) + ($a1-$a0)*$cycles + $a0")
println("f($cycles) = $solution")
println("gardenPlotsReached($steps) = $solution")
return solution
}
private data class Point(val row: Int, val column: Int) {
fun neighbours(): Set<Point> {
return setOf(
Point(row - 1, column),
Point(row + 1, column),
Point(row, column - 1),
Point(row, column + 1)
)
}
}
private fun List<String>.getStartingPoint(): Point {
return this.flatMapIndexed { row, line ->
line.mapIndexed { column, c ->
if (c == 'S') Point(row, column) else null
}.filterNotNull()
}.first()
}
private fun List<String>.gardenPlotsReached(steps: Int): Int {
val start = this.getStartingPoint()
var reached = setOf(start)
(1..steps).forEach { _ ->
reached = reached.flatMap { pointReached ->
pointReached.neighbours().filter { neighbour ->
val row = neighbour.row.mod(this.size)
val column = neighbour.column.mod(this[0].length)
this[row][column] != '#'
}
}.toSet()
}
return reached.size
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 2,468 | advent-of-code | MIT License |
src/main/kotlin/at/mpichler/aoc/solutions/year2023/Day02.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2023
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
open class Part2A : PartSolution() {
internal lateinit var games: List<Game>
override fun parseInput(text: String) {
games = text.trim().split("\n").map { Game(it) }
}
override fun getExampleAnswer() = 8
override fun compute(): Int {
return games.filter { it.valid }.sumOf { it.id }
}
internal data class Game(val id: Int, val rounds: List<Round>) {
val valid get() = rounds.all { it.valid }
private val minRed get() = rounds.maxOf { it.red }
private val minGreen get() = rounds.maxOf { it.green }
private val minBlue get() = rounds.maxOf { it.blue }
val power get() = minRed * minGreen * minBlue
}
internal data class Round(val red: Int, val green: Int, val blue: Int) {
val sum get() = red + green + blue
val valid = !(sum > 39 || red > 12 || green > 13 || blue > 14)
}
private fun Game(text: String): Game {
val match = "Game (\\d+): (.*)".toRegex().find(text)
match as MatchResult
val id = match.groupValues[1].toInt()
val result = match.groupValues[2]
val r = result.split("; ")
val rounds = mutableListOf<Round>()
for (round in r) {
var red = 0
var green = 0
var blue = 0
val cubes = round.split(", ")
for (cube in cubes) {
when {
cube.endsWith("red") -> red += cube.replace(" red", "").toInt()
cube.endsWith("green") -> green += cube.replace(" green", "").toInt()
cube.endsWith("blue") -> blue += cube.replace(" blue", "").toInt()
}
}
rounds.add(Round(red, green, blue))
}
return Game(id, rounds)
}
}
class Part2B : Part2A() {
override fun getExampleAnswer() = 2286
override fun compute(): Int {
return games.sumOf { it.power }
}
}
fun main() {
Day(2023, 2, Part2A(), Part2B())
}
| 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 2,107 | advent-of-code-kotlin | MIT License |
src/Day01.kt | muellerml | 573,601,715 | false | {"Kotlin": 14872} | fun main() {
fun part1(input: List<String>): Int {
return input.foldIndexed(Calories(0, 0)) { index, calories, addition ->
when (val addToInt = addition.toIntOrNull()) {
null -> if (calories.max < calories.current) {
println("Highest value found for index $index")
calories.copy(max = calories.current, current = 0)
} else Calories(calories.max, 0)
else -> calories.copy(current = calories.current + addToInt)
}
}.max
}
fun part2(input: List<String>): Int {
val elves: MutableList<Elf> = mutableListOf()
input.foldIndexed(Elf(0)) { index, elf, calories: String ->
val addToCalories = calories.toIntOrNull()
println(index)
when {
addToCalories == null -> {
elves.add(elf)
Elf(0)
}
index == (input.size - 1) -> {
elves.add(elf.copy(calories = elf.calories + addToCalories))
Elf(0)
}
else -> elf.copy(calories = elf.calories + addToCalories)
}
}
return elves.sortedByDescending { it.calories }.take(3).sumOf { it.calories }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
val result = part1(testInput)
check(result == 24000)
val result2 = part2(testInput)
check(result2 == 45000)
val input = readInput("Day01")
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
data class Calories(val max: Int, val current: Int)
data class Elf(val calories: Int)
| 0 | Kotlin | 0 | 0 | 028ae0751d041491009ed361962962a64f18e7ab | 1,753 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day5.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.InputParser
import java.lang.RuntimeException
data class CategoryMap(val source: LongRange, val dest: LongRange)
data class Almanac(
val seeds: List<Long>,
val maps: List<List<CategoryMap>>,
)
data class AlmanacPart2(
val seeds: List<LongRange>,
val maps: List<List<CategoryMap>>,
)
private fun parseCategoryMappings(input: String) = input.split("\n.*map:".toRegex()).drop(1)
.map { map ->
map.trim().split("\n").map { range ->
range.split(" ")
.map { it.toLong() }
.let {
CategoryMap(
dest = LongRange(it[0], it[0] + it[2] - 1),
source = LongRange(it[1], it[1] + it[2] - 1),
)
}
}.sortedBy { it.source.first }
}
object AlmanacParser : InputParser<Almanac> {
override fun parse(input: String) = Almanac(
seeds = "seeds: (.*)".toRegex().find(input)!!.groupValues[1].split(" ").map { it.toLong() },
maps = parseCategoryMappings(input)
)
}
object AlmanacParserPart2 : InputParser<AlmanacPart2> {
override fun parse(input: String) = AlmanacPart2(
seeds = "seeds: (.*)".toRegex().find(input)!!.groupValues[1]
.split(" ")
.map { it.toLong() }
.windowed(2, step = 2).map { LongRange(it[0], it[0] + (it[1] - 1)) },
maps = parseCategoryMappings(input)
)
}
fun main() {
aoc {
puzzle { 2023 day 5 }
fun Almanac.locationForSeed(seed: Long): Long {
var current = seed
maps.forEach { map ->
val transform = map
.firstOrNull { it.source.contains(current) }
?: CategoryMap(seed..seed, seed..seed)
current = (current - transform.source.first) + transform.dest.first
}
return current
}
part1 { input ->
val almanac = AlmanacParser.parse(input)
almanac.seeds.minOf { almanac.locationForSeed(it) }
}
fun LongRange.splitLeft(splitpoint: Long): List<LongRange> {
return if (splitpoint - 1 in this) {
listOf(
LongRange(first, splitpoint - 1),
LongRange(splitpoint, last)
)
} else throw RuntimeException()
}
fun LongRange.splitRight(splitpoint: Long): List<LongRange> {
return if (splitpoint + 1 in this) {
listOf(
LongRange(first, splitpoint),
LongRange(splitpoint + 1, last)
)
} else throw RuntimeException()
}
fun nextLevel(input: List<LongRange>, maps: List<List<CategoryMap>>, level: Int): List<LongRange> {
if (level == maps.size) return input
val currentMaps = maps[level]
val leftSplit = input.flatMap { range ->
currentMaps.find { map -> map.source.first > range.first && map.source.first <= range.last }
?.let { match -> range.splitLeft(match.source.first) }
?: listOf(range)
}.toSet()
val rightSplit = leftSplit.flatMap { range ->
currentMaps.find { map -> map.source.last >= range.first && map.source.last < range.last }
?.let { match ->
range.splitRight(match.source.last)
}
?: listOf(range)
}.toSet()
val output = rightSplit.map {
currentMaps.firstOrNull { map -> map.source.contains(it.first) }?.let { match ->
val offset = match.dest.first - match.source.first
LongRange(it.first + offset, it.last + offset)
} ?: it
}
return nextLevel(output, maps, level + 1)
}
part2 { input ->
val almanac = AlmanacParserPart2.parse(input)
nextLevel(almanac.seeds, almanac.maps, 0).minOf { it.first }
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 4,235 | aoc-2023 | The Unlicense |
src/Day05.kt | winnerwinter | 573,917,144 | false | {"Kotlin": 20685} | fun main() {
fun parseInstruction(input: String): Instruction {
val instructionParts = input.split(" ")
val move = instructionParts[1].toInt()
val from = instructionParts[3].toInt()
val to = instructionParts[5].toInt()
return Triple(move, from, to)
}
fun parseInput(input: List<String>): Pair<State, List<Instruction>> {
val instructionSep = input.indexOf("")
val diagram = input.subList(0, instructionSep - 1)
val stackLabels = input.subList(instructionSep - 1, instructionSep)
val instructionStrings = input.subList(instructionSep + 1, input.size)
val numStacks = stackLabels.single().last().toString().toInt()
val stackMap = (1 .. numStacks).associateWith { i ->
val diagramI = ((i - 1) * 4) + 1
diagram.mapNotNull { it.getOrNull(diagramI)?.takeIf { it != ' ' } }.reversed()
}
val instructions = instructionStrings.map { parseInstruction(it) }
return stackMap to instructions
}
fun State.moveNBox(from: Int, to: Int, n: Int): State {
val crateIds = requireNotNull(this[from]?.takeLast(n))
return this.mapValues { (stackId, stack) ->
when (stackId) {
from -> stack.dropLast(n)
to -> listOf(*stack.toTypedArray(), *crateIds.toTypedArray())
else -> stack
}
}
}
fun State.applyInstruction(instruction: Instruction, crateMover: CrateMover): State {
val (move, from, to) = instruction
return when (crateMover) {
CrateMover.v9000 -> (0 until move).fold(this) { acc, _ -> acc.moveNBox(from, to, 1) }
CrateMover.v9001 -> this.moveNBox(from, to, move)
}
}
fun State.compute(instructions: List<Instruction>, crateMover: CrateMover): String =
instructions.fold(this) { acc, instruction -> acc.applyInstruction(instruction, crateMover) }.let {
it.values.map { it.last() }.joinToString("")
}
fun part1(): String {
val testInput = readInput("Day05_test")
val test_ans = parseInput(testInput).let { (state, instructions) -> state.compute(instructions, CrateMover.v9000) }
check(test_ans == "CMZ")
val input = readInput("Day05")
val ans = parseInput(input).let { (state, instructions) -> state.compute(instructions, CrateMover.v9000) }
return ans
}
fun part2(): String {
val testInput = readInput("Day05_test")
val test_ans = parseInput(testInput).let { (state, instructions) -> state.compute(instructions, CrateMover.v9001) }
check(test_ans == "MCD")
val input = readInput("Day05")
val ans = parseInput(input).let { (state, instructions) -> state.compute(instructions, CrateMover.v9001) }
return ans
}
println(part1())
println(part2())
}
typealias State = Map<Int, List<Char>>
typealias Instruction = Triple<Int, Int, Int>
enum class CrateMover {
v9000,
v9001
}
| 0 | Kotlin | 0 | 0 | a019e5006998224748bcafc1c07011cc1f02aa50 | 3,038 | advent-of-code-22 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.