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/day08/Day08.kt | pientaa | 572,927,825 | false | {"Kotlin": 19922} | package day08
import readLines
fun main() {
fun part1(input: List<String>): Int {
val transposedInput = input
.transpose()
return input
.mapIndexed { rowIndex, row ->
row.mapIndexed { columnIndex, c ->
val column = transposedInput[columnIndex]
when {
(columnIndex == 0 || columnIndex == row.length - 1) -> 1
(rowIndex == 0 || rowIndex == input.size - 1) -> 1
row.substring(0 until columnIndex).all { it < c } -> 1 //left
row.substring(columnIndex + 1).all { it < c } -> 1 //right
column.substring(0 until rowIndex).all { it < c } -> 1 //up
column.substring(rowIndex + 1).all { it < c } -> 1 //up
else -> 0
}
}
}
.flatten()
.sum()
}
fun part2(input: List<String>): Int {
val transposedInput = input
.transpose()
return input
.mapIndexed { rowIndex, row ->
row.mapIndexed { columnIndex, c ->
val column = transposedInput[columnIndex]
val up = column.substring(0 until rowIndex).reversed()
.getDistance(c)
val down = column.substring(rowIndex + 1)
.getDistance(c)
val left = row.substring(0 until columnIndex).reversed()
.getDistance(c)
val right = row.substring(columnIndex + 1)
.getDistance(c)
up * down * right * left
}
}
.flatten()
.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("day08/Day08_test")
val input = readLines("day08/Day08")
println(part1(input))
println(part2(input))
}
private fun String.getDistance(tree: Char) =
fold(0) { acc, nextTree ->
if (nextTree >= tree) {
return acc + 1
} else acc + 1
}
fun List<String>.transpose(): List<String> {
val ret: MutableList<String> = ArrayList()
val n = this[0].length
for (i in 0 until n) {
val col: MutableList<Char> = ArrayList()
for (row in this) {
col.add(row[i])
}
ret.add(col.fold("") { acc, c -> acc + c })
}
return ret
}
| 0 | Kotlin | 0 | 0 | 63094d8d1887d33b78e2dd73f917d46ca1cbaf9c | 2,547 | aoc-2022-in-kotlin | Apache License 2.0 |
src/y2023/Day25.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2023
import util.readInput
import util.timingStatistics
object Day25 {
private fun parse(input: List<String>): List<Pair<String, String>> {
return input.flatMap { line ->
val (p1, p2) = line.split(": ")
p2.split(" ").flatMap {
listOf(p1 to it, it to p1)
}
}
}
fun part1(input: List<String>): Int {
val edges = parse(input)
val lookup = edges.groupBy { it.first }.mapValues { (_, v) -> v.map { it.second } }
var components = calculateRandomizedConnectedComponents(edges, lookup)
while (components.size != 2) {
components = calculateRandomizedConnectedComponents(edges, lookup)
}
return components.first().size * components.last().size
}
private fun calculateRandomizedConnectedComponents(
edges: List<Pair<String, String>>,
lookup: Map<String, List<String>>
): List<Set<String>> {
val edgeUseCount = edges.associateWith { 0 }.toMutableMap()
val randomStartStop = lookup.keys.toList().shuffled().zipWithNext()
randomStartStop.forEach { (n1, n2) ->
shortestPathEdges(n1, n2, lookup).forEach { edge ->
edgeUseCount[edge] = edgeUseCount[edge]!! + 1
}
}
val consolidatedEdges = edgeUseCount.mapValues { (edge, count) ->
if (edge.first < edge.second) {
count + edgeUseCount[edge.second to edge.first]!!
} else {
0
}
}
val cutEdges = consolidatedEdges.entries.sortedByDescending { it.value }.take(3).map { it.key }
val splitGraph = lookup.toMutableMap()
cutEdges.forEach { (n1, n2) ->
splitGraph[n1] = splitGraph[n1]!!.filter { it != n2 }
splitGraph[n2] = splitGraph[n2]!!.filter { it != n1 }
}
return connectedComponents(splitGraph)
}
private fun connectedComponents(splitGraph: MutableMap<String, List<String>>): List<Set<String>> {
val rtn = mutableListOf<Set<String>>()
val remaining = splitGraph.keys.toMutableSet()
while (remaining.isNotEmpty()) {
val start = remaining.first()
var frontier = setOf(start)
val component = mutableSetOf(start)
while (frontier.isNotEmpty()) {
frontier = frontier.flatMap { node ->
splitGraph[node]!!.filter { it in remaining }
}.toSet()
component.addAll(frontier)
remaining.removeAll(frontier)
}
rtn.add(component)
}
return rtn
}
private fun shortestPathEdges(node1: String, node2: String, graph: Map<String, List<String>>): List<Pair<String, String>> {
val path = shortestPath(node1, node2, graph)
return path.zipWithNext()
}
private fun shortestPath(node1: String, node2: String, graph: Map<String, List<String>>): List<String> {
val visited = mutableSetOf(node1)
var paths = listOf(listOf(node1))
while (true) {
paths = paths.flatMap { path ->
val last = path.last()
val nexts = graph[last]!!.filter { it !in visited }
visited.addAll(nexts)
if (node2 in nexts) {
return path + node2
}
nexts.map { next ->
path + next
}
}
}
}
}
fun main() {
val testInput = """
jqt: rhn xhk nvd
rsh: frs pzl lsr
xhk: hfx
cmg: qnr nvd lhk bvb
rhn: xhk bvb hfx
bvb: xhk hfx
pzl: lsr hfx nvd
qnr: nvd
ntq: jqt hfx bvb xhk
nvd: lhk
lsr: lhk
rzs: qnr cmg lsr rsh
frs: qnr lhk lsr
""".trimIndent().split("\n")
println("------Tests------")
println(Day25.part1(testInput))
println("------Real------")
val input = readInput(2023, 25)
println("Part 1 result: ${Day25.part1(input)}")
timingStatistics { Day25.part1(input) }
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 4,120 | advent-of-code | Apache License 2.0 |
src/main/year_2017/day07/day07.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package year_2017.day07
import kotlin.math.absoluteValue
import readInput
import second
fun part1(input: List<String>): String {
val programs = input.map(String::parse)
return programs.findBottomProgram()
}
fun part2(input: List<String>): Int {
val programs = input.map(String::parse)
allPrograms = programs.associateBy { it.name }.toMutableMap()
return allPrograms[programs.findBottomProgram()]!!.findImbalance()
}
var allPrograms: Map<String, Program> = mapOf()
fun main() {
val input = readInput("main/year_2017/day07/Day07")
println(part1(input))
println(part2(input))
}
fun Collection<Program>.findBottomProgram(): String {
val allNames = this.flatMap { p -> listOf(p.name.trim()) + p.programsCarried.map { it.trim() } }
val nameCounts = allNames.associateBy { s -> allNames.count { it == s } }
return nameCounts[1]!!
}
data class Program(
val name: String,
val weight: Int,
val programsCarried: List<String>
) {
private fun totalWeightCarried(): Int {
return weight + programsCarried
.sumOf { name ->
allPrograms[name.trim()]!!.totalWeightCarried()
}
}
private fun childrenAreBalanced() =
programsCarried.map { allPrograms[it.trim()]!!.totalWeightCarried() }.distinct().size == 1
fun findImbalance(imbalance: Int? = null): Int =
if (imbalance != null && childrenAreBalanced()) {
weight - imbalance
} else {
val subTrees = programsCarried.groupBy { allPrograms[it.trim()]!!.totalWeightCarried() }
val outOfBalanceTree = subTrees.minBy { it.value.size }.value.first().trim()
allPrograms[outOfBalanceTree]!!.findImbalance(imbalance = imbalance ?: subTrees.keys.reduce { a, b -> a - b }.absoluteValue)
}
}
fun String.parse(): Program {
return this.split("->").let {
val split = it.first().split((" ("))
val name = split.first().trim()
val weight = split.second().trim().dropLast(1).toInt()
val programs = if (it.size > 1) {
it.second().split((", ").trim())
} else emptyList()
Program(name.trim(), weight, programs.map(String::trim))
}
} | 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 2,220 | aoc-2022 | Apache License 2.0 |
src/Day08.kt | Arclights | 574,085,358 | false | {"Kotlin": 11490} | fun main() {
fun <T> List<List<T>>.transpose(): List<List<T>> = this
.drop(1)
.fold(this.first().map { listOf(it) }) { transposed, row ->
transposed.zip(row) { l, r -> l.plus(r) }
}
fun <T> List<List<T>>.asMatrixString() = this.joinToString("\n") { row -> row.joinToString("") }
fun findVisible(trees: List<Tree>, comparer: (Int, Int) -> Boolean) = trees
.fold(listOf<Tree>()) { previousTrees, tree ->
if (previousTrees.isEmpty() || comparer(tree.height, previousTrees.last().height)) {
previousTrees.plus(tree)
} else {
previousTrees
}
}
fun findVisibleFromEdge(trees: List<Tree>) = findVisible(trees) { a, b -> a > b }
fun findVisibleFromTree(trees: List<Tree>, currentTreeHeight: Int) =
findVisible(trees) { _, b -> b < currentTreeHeight }
fun findVisible(input: List<List<Tree>>): Set<Tree> {
return input.indices
.flatMap { row ->
listOf(
findVisibleFromEdge(input[row]),
findVisibleFromEdge(input[row].reversed())
).flatten()
}
.toSet()
}
fun part1(input: List<List<Tree>>): Int = listOf(
findVisible(input),
findVisible(input.transpose())
)
.flatten()
.toSet()
.size
fun scenicScore(input: List<List<Tree>>, row: Int, column: Int): Int {
val transposed = input.transpose()
val currentTreeHeight = input[row][column].height
return listOf(
input[row].drop(column + 1),
input[row].reversed().drop(input[row].size - column),
transposed[column].drop(row + 1),
transposed[column].reversed().drop(transposed[column].size - row)
)
.map { findVisibleFromTree(it, currentTreeHeight) }
.map { it.size }
.reduce(Int::times)
}
fun part2(input: List<List<Tree>>): Int {
return input.indices
.flatMap { row ->
input.first().indices.map { column -> scenicScore(input, row, column) }
}
.max()
}
fun parseInput(input: List<String>) = input.mapIndexed { row, line ->
line.mapIndexed { column, treeHeight ->
Tree(treeHeight.digitToInt(), row, column)
}
}
val testInput = readInput("Day08_test")
val parsedTestInput = parseInput(testInput)
println(part1(parsedTestInput))
println(part2(parsedTestInput))
println()
val input = readInput("Day08")
val parsedInput = parseInput(input)
println(part1(parsedInput))
println(part2(parsedInput))
}
data class Tree(val height: Int, val row: Int, val column: Int) {
override fun toString(): String {
return "($height, $row, $column)"
}
} | 0 | Kotlin | 0 | 0 | 121a81ba82ba0d921bd1b689241ffa8727bc806e | 2,875 | advent_of_code_2022 | Apache License 2.0 |
advent-of-code-2023/src/Day22.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 kotlin.math.abs
import kotlin.math.min
private const val DAY = "Day22"
fun main() {
fun testInput() = readInput("${DAY}_test")
fun input() = readInput(DAY)
"Part 1" {
part1(testInput()) shouldBe 5
measureAnswer { part1(input()) }
}
"Part 2" {
part2(testInput()) shouldBe 7
measureAnswer { part2(input()) }
}
}
private fun part1(input: List<SandBrick>): Int {
val graph = buildGraph(input)
return graph.count { node -> node.nextNodes().none { it.previousNodes().count() == 1 } }
}
private fun part2(input: List<SandBrick>): Int {
val graph = buildGraph(input)
return graph.sumOf { startNode ->
val queue = ArrayDeque<GraphNode<SandBrick>>()
val visited = mutableSetOf<GraphNode<SandBrick>>()
fun addNextNode(nextNode: GraphNode<SandBrick>) {
if (visited.add(nextNode)) queue.addLast(nextNode)
}
addNextNode(startNode)
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
node.nextNodes()
.filter { nextNode -> nextNode.previousNodes().all { it in visited } }
.forEach(::addNextNode)
}
visited.size - 1
}
}
private fun buildGraph(bricks: List<SandBrick>): Graph<SandBrick> {
val graph = Graph<SandBrick>()
val topBricks = mutableMapOf<XY, GraphNode<SandBrick>>()
for (brick in bricks.sortedBy { it.z1 }) {
val node = GraphNode(brick)
val xyPoints = brick.xyPoints()
val previousBricks = mutableSetOf<GraphNode<SandBrick>>()
var topZ = 0
for (previousBrick in xyPoints.mapNotNull { topBricks[it] }) {
val currentZ = previousBrick.value.z2
if (currentZ > topZ) {
topZ = currentZ
previousBricks.clear()
}
if (currentZ == topZ) previousBricks += previousBrick
}
node.value.z1 = topZ + 1
previousBricks.forEach { it.connectToNext(node) }
graph += node
for (xy in xyPoints) topBricks[xy] = node
}
return graph
}
private fun readInput(name: String) = readLines(name) { line ->
val (x1, y1, z1, x2, y2, z2) = line.splitInts(",", "~")
SandBrick(x1, y1, z1, x2, y2, z2)
}
private class SandBrick(
x1: Int,
y1: Int,
z1: Int,
x2: Int,
y2: Int,
z2: Int,
) {
val xRange = x1..x2
val yRange = y1..y2
val height = abs(z2 - z1) + 1
var z1 = min(z1, z2)
val z2 get() = z1 + height - 1
fun xyPoints(): List<XY> = xRange.flatMap { x -> yRange.map { y -> XY(x, y) } }
}
private data class XY(val x: Int, val y: Int)
private operator fun <E> List<E>.component6() = get(5)
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 2,827 | advent-of-code | Apache License 2.0 |
src/Day03.kt | peterfortuin | 573,120,586 | false | {"Kotlin": 22151} | fun main() {
fun part1(input: List<String>): Int {
val incorrectSupplies = input.map { line ->
val l = line.toCharArray().map {
charToNumber(it)
}
val twoBags = Pair(l.subList(0, l.size / 2), l.subList(l.size / 2, l.size))
findItemInBothLists(twoBags.first, twoBags.second)
}
return incorrectSupplies.sum()
}
fun part2(input: List<String>): Int {
return input.devideInGroupsOf3Lines()
.map { group ->
group.findUniqueItemInAllLines()
}.sumOf { item -> charToNumber(item) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println("Part 1 = ${part1(input)}")
println("Part 2 = ${part2(input)}")
}
fun findItemInBothLists(first: List<Int>, second: List<Int>): Int {
val firstSet = first.toSet()
val secondSet = second.toSet()
return firstSet.intersect(secondSet).first()
}
fun charToNumber(it: Char) = when (it.code) {
in 97..122 -> it.code - 96
in 65..90 -> it.code - 38
else -> 0
}
private fun List<String>.findUniqueItemInAllLines(): Char {
val firstSet = this[0].toSet()
val secondSet = this[1].toSet()
val thirdSet = this[2].toSet()
val intersect = firstSet.intersect(secondSet).intersect(thirdSet)
return intersect.first()
}
private fun <E> List<E>.devideInGroupsOf3Lines(): List<List<E>> {
val result = mutableListOf<List<E>>()
var i = 0
while (i < this.size) {
result.add(this.subList(i, i + 3))
i += 3
}
return result
}
| 0 | Kotlin | 0 | 0 | c92a8260e0b124e4da55ac6622d4fe80138c5e64 | 1,748 | advent-of-code-2022 | Apache License 2.0 |
y2018/src/main/kotlin/adventofcode/y2018/Day24.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2018
import adventofcode.io.AdventSolution
fun main() = Day24.solve()
object Day24 : AdventSolution(2018, 24, "Immune System Simulator 20XX") {
override fun solvePartOne(input: String): Int {
val (immune, disease) = parse(input).chunked(10).toList()
val (remI, remD) = runCombat(immune, disease)
return maxOf(remI, remD)
}
override fun solvePartTwo(input: String): Int {
val (immune, disease) = parse(input).chunked(10).toList()
val x = 61 //binary search run by hand for now
val (remI, _) = runCombat(immune.map { it.copy(damage = it.damage + x) }, disease)
return remI
}
private fun runCombat(immune: List<Group>, disease: List<Group>): Pair<Int, Int> {
while (immune.any { it.count > 0 } && disease.any { it.count > 0 }) {
(selectTargets(immune, disease) + selectTargets(disease, immune))
.sortedByDescending { it.first.initiative }
.forEach { (att, def) -> att.dealDamage(def) }
}
return Pair(immune.sumOf(Group::count), disease.sumOf(Group::count))
}
private fun selectTargets(attackers: List<Group>, defenders: List<Group>): List<Pair<Group, Group>> {
val validTargets = defenders.filter { it.count > 0 }.toMutableSet()
return attackers
.sortedWith(compareByDescending(Group::effectivePower).thenByDescending(Group::initiative))
.mapNotNull { attacker ->
attacker.chooseTarget(validTargets)?.let { target ->
validTargets -= target
attacker to target
}
}
}
}
private data class Group(
var count: Int,
val hp: Int,
val weak: Set<Damage>,
val immune: Set<Damage>,
val damage: Int,
val type: Damage,
val initiative: Int
) {
fun effectivePower() = count * damage
fun chooseTarget(targets: Iterable<Group>): Group? {
return targets.sortedWith(compareByDescending(Group::effectivePower).thenByDescending(Group::initiative))
.maxByOrNull(this::calcDamage)
?.takeUnless { calcDamage(it) == 0 }
}
fun dealDamage(target: Group) {
target.count -= minOf(calcDamage(target) / target.hp, target.count)
}
private fun calcDamage(target: Group) =
when (type) {
in target.immune -> 0
in target.weak -> effectivePower() * 2
else -> effectivePower()
}
}
private enum class Damage { Slashing, Bludgeoning, Cold, Fire, Radiation }
private fun String.toDamageType() = Damage.valueOf(replaceFirstChar(Char::titlecase))
private fun parse(input: String): Sequence<Group> {
val regex = "(\\d+) units each with (\\d+) hit points(.*) with an attack that does (\\d+) (.*) damage at initiative (\\d+)".toRegex()
return input
.lineSequence()
.map { regex.matchEntire(it) }
.filterNotNull()
.map { it.destructured }
.map { (c, h, imm, d, t, i) ->
val weak = imm.parseImmunityList("weak")
val immune = imm.parseImmunityList("immune")
Group(c.toInt(), h.toInt(), weak, immune, d.toInt(), t.toDamageType(), i.toInt())
}
}
private fun String.parseImmunityList(modifier: String) =
substringAfter("$modifier to ", "")
.substringBefore(';')
.trim(' ', ')')
.splitToSequence(", ")
.filter { it.isNotBlank() }
.map { it.toDamageType() }
.toSet() | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 3,695 | advent-of-code | MIT License |
src/day8/Day08.kt | JoeSkedulo | 573,328,678 | false | {"Kotlin": 69788} | package day8
import Runner
fun main() {
Day8Runner().solve()
}
class Day8Runner : Runner<Int>(
day = 8,
expectedPartOneTestAnswer = 21,
expectedPartTwoTestAnswer = 8
) {
override fun partOne(input: List<String>, test: Boolean): Int {
val rows = rowsOfTrees(input)
val columns = columnsOfTrees(rows)
return visibleTreesFromEdge(rows, columns)
.distinctBy { it.coord }
.count()
}
override fun partTwo(input: List<String>, test: Boolean): Int {
val rows = rowsOfTrees(input)
val columns = columnsOfTrees(rows)
val allTress = (columns + rows).flatten().distinctBy { it.coord }
return allTress.maxOf { tree ->
scenicScore(
tree = tree,
rows = rows,
columns = columns
)
}
}
private fun scenicScore(tree: Tree, rows: List<List<Tree>>, columns: List<List<Tree>>) : Int {
val x = tree.coord.split(":")[0].toInt()
val y = tree.coord.split(":")[1].toInt()
val xForward = rows[x].subList(y + 1, rows.size)
val yForward = columns[y].subList(x + 1, columns.size)
val xBackward = rows[x].subList(0, y).reversed()
val yBackward = columns[y].subList(0, x).reversed()
return xForward.countVisibleTrees(tree.height) *
yForward.countVisibleTrees(tree.height) *
xBackward.countVisibleTrees(tree.height) *
yBackward.countVisibleTrees(tree.height)
}
private fun List<Tree>.countVisibleTrees(height: Int) : Int = let { trees ->
when (val first = trees.indexOfFirst { it.height >= height } ) {
-1 -> trees.count()
else -> first + 1
}
}
private fun visibleTreesFromEdge(rows: List<List<Tree>>, columns: List<List<Tree>>) : List<Tree> {
return mapToVisible(rows) +
mapToVisible(rows, true) +
mapToVisible(columns) +
mapToVisible(columns, true)
}
private fun mapToVisible(input: List<List<Tree>>, reverse: Boolean = false) : List<Tree> {
return input.flatMap { row ->
val r = if (reverse) {
row.reversed()
} else {
row
}
r.filterIndexed { index, tree ->
val subset = r.subList(0, index)
subset.isEmpty() || tree.height > subset.maxOf { it.height }
}
}
}
private fun rowsOfTrees(input: List<String>): List<List<Tree>> {
return input.mapIndexed { i, line ->
line.mapIndexed { j, char ->
Tree(
height = char.toString().toInt(),
coord = "$i:$j"
)
}
}
}
private fun columnsOfTrees(rows: List<List<Tree>>) : List<List<Tree>> {
return buildList {
repeat (rows.first().count()) { i ->
add(rows.mapIndexed { j, row ->
Tree(
height = row[i].height,
coord = "$j:$i"
)
})
}
}
}
}
data class Tree(
val height: Int,
val coord: String
)
| 0 | Kotlin | 0 | 0 | bd8f4058cef195804c7a057473998bf80b88b781 | 3,247 | advent-of-code | Apache License 2.0 |
src/day11/Day11.kt | xxfast | 572,724,963 | false | {"Kotlin": 32696} | package day11
import readText
data class Monkey(
var items: MutableList<Long>, val operation: (Long) -> Long, val test: Long,
val ifTrue: Int, val ifFalse: Int, var inspected: Int = 0
)
fun format(input: String): List<Monkey> = input.split("\n\n")
.map { description ->
val descriptions = description.split("\n")
Monkey(
items = descriptions[1].substringAfter(":")
.trim().split(",").map { it.trim().toLong() }.toMutableList(),
operation = descriptions[2].let { line ->
val lastWord = line.split(" ").last().trim()
val number = if (lastWord == "old") null else lastWord.trim().toLong()
if (line.contains("*")) { worry -> worry * (number ?: worry) }
else { worry -> worry + (number ?: worry) }
},
test = descriptions[3].split(" ").last().trim().toLong(),
ifTrue = descriptions[4].split(" ").last().trim().toInt(),
ifFalse = descriptions[5].split(" ").last().trim().toInt(),
)
}
fun List<Monkey>.score(): Long = this
.sortedByDescending { it.inspected }.take(2)
.let { (top, second) -> top.inspected.toLong() * second.inspected.toLong() }
fun List<Monkey>.game(round: Int, manage: List<Monkey>.(worry: Long) -> Long) = apply {
repeat(round) {
forEach { monkey ->
monkey.items.toList().forEach { worry ->
monkey.items.remove(worry)
val inspection: Long = manage(monkey.operation(worry))
val test: Boolean = inspection % monkey.test == 0L
val next: Int = if (test) monkey.ifTrue else monkey.ifFalse
get(next).items += inspection
monkey.inspected++
}
}
}
}
val List<Monkey>.commonTest: Long
get() =
map { it.test }.reduce { divider, test -> divider * test }
fun main() {
fun part1(input: String): Long = format(input)
.game(20) { worry -> worry / 3 }
.score()
fun part2(input: String): Long = format(input)
.game(10000) { worry -> worry % commonTest }
.score()
val testInput = readText("day11/test.txt")
val input = readText("day11/input.txt")
check(part1(testInput) == 10605L)
println(part1(input))
check(part2(testInput) == 2713310158L)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | a8c40224ec25b7f3739da144cbbb25c505eab2e4 | 2,179 | advent-of-code-22 | Apache License 2.0 |
src/Day08.kt | ThijsBoehme | 572,628,902 | false | {"Kotlin": 16547} | fun main() {
fun part1(rows: List<String>): Int {
val size = rows.size
val grid = rows.map { it.toList().map { tree -> tree.digitToInt() } }
return grid.mapIndexed { rowNumber, row ->
row.mapIndexed { columnNumber, tree ->
val visibleFromLeft = tree > (row.take(columnNumber).maxOrNull() ?: -1)
val visibleFromRight = tree > (row.takeLast(size - columnNumber - 1).maxOrNull() ?: -1)
val visibleFromTop = tree > (grid.take(rowNumber).maxOfOrNull { it[columnNumber] } ?: -1)
val visibleFromBottom =
tree > (grid.takeLast(size - rowNumber - 1).maxOfOrNull { it[columnNumber] } ?: -1)
visibleFromLeft
|| visibleFromRight
|| visibleFromTop
|| visibleFromBottom
}.count { it }
}.sum()
}
fun part2(rows: List<String>): Int {
val size = rows.size
val grid = rows.map { it.toList().map { tree -> tree.digitToInt() } }
return grid.mapIndexed { rowNumber, row ->
row.mapIndexed { columnNumber, tree ->
var viewDistanceLeft = if (columnNumber == 0) 0
else row.take(columnNumber).takeLastWhile { it < tree }.size
if (row.take(columnNumber).any { it >= tree }) viewDistanceLeft += 1
var viewDistanceRight = if (columnNumber == size - 1) 0
else row.takeLast(size - columnNumber - 1).takeWhile { it < tree }.size
if (row.takeLast(size - columnNumber - 1).any { it >= tree }) viewDistanceRight += 1
var viewDistanceTop = if (rowNumber == 0) 0
else grid.take(rowNumber).takeLastWhile { it[columnNumber] < tree }.size
if (grid.take(rowNumber).any { it[columnNumber] >= tree }) viewDistanceTop += 1
var viewDistanceBottom = if (rowNumber == size - 1) 0
else grid.takeLast(size - rowNumber - 1).takeWhile { it[columnNumber] < tree }.size
if (grid.takeLast(size - rowNumber - 1).any { it[columnNumber] >= tree }) viewDistanceBottom += 1
viewDistanceLeft * viewDistanceRight * viewDistanceTop * viewDistanceBottom
}.max()
}.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 707e96ec77972145fd050f5c6de352cb92c55937 | 2,597 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day08.kt | timj11dude | 572,900,585 | false | {"Kotlin": 15953} | typealias Forest = List<List<Tree>>
data class Tree(val x: Int, val y: Int, val h: Int, val v: Boolean = false, val s: Int = 0)
fun List<List<Tree>>.rotate() = List(size) { rowI ->
List(first().size) { colI ->
this[first().size - 1 - colI][rowI]
}
}
fun main() {
fun parseInput(input: Collection<String>): Forest {
return input.mapIndexed { rowI, row ->
row.mapIndexed { colI, h ->
Tree(colI, rowI, h.digitToInt())
}
}
}
fun checkLine(input: Collection<Tree>): List<Tree> {
return input.fold(-1 to emptyList<Tree>()) { (h, out), tree ->
when (tree.h > h) {
true -> tree.h to out + tree.copy(v = true)
false -> h to out + tree
}
}.second
}
fun part1(input: Collection<String>): Int {
val forest = parseInput(input)
.map(::checkLine).rotate()
.map(::checkLine).rotate()
.map(::checkLine).rotate()
.map(::checkLine).rotate()
return forest.flatten().count { it.v }
}
fun Forest.checkViewFrom(tree: Tree): Int {
val row = this[tree.y]
val col = this.rotate()[tree.x].reversed()
fun List<Tree>.countLine(t: Int): Int {
fun List<Tree>.takeVisibleTrees() = take(indexOfFirst { it.h >= tree.h }.takeUnless { it == -1 }?.let { it + 1 } ?: size)
return drop(t + 1).takeVisibleTrees().count() * take(t).reversed().takeVisibleTrees().count()
}
return (col.countLine(tree.y) * row.countLine(tree.x))
}
fun part2(input: Collection<String>): Int {
val forest = parseInput(input)
return forest.flatten().maxOf { forest.checkViewFrom(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21) { "Check Failed. Returned Value: ${part1(testInput)}" }
check(part2(testInput) == 8) { "Check Failed. Returned Value: ${part2(testInput)}" }
val input = readInput("Day08")
println(part1(input))
println(part2(input))
// wrong guess: 545729
}
| 0 | Kotlin | 0 | 0 | 28aa4518ea861bd1b60463b23def22e70b1ed481 | 2,173 | advent-of-code-2022 | Apache License 2.0 |
src/year_2021/day_08/Day08.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2021.day_08
import readInput
data class Puzzle(
val uniqueNumbers: List<ClockNumber>,
val toSolve: List<ClockNumber>
)
data class ClockNumber(
val segments: List<Char>
)
object Day08 {
/**
* @return
*/
fun solutionOne(text: List<String>): Int {
val puzzles = parseText(text)
return puzzles.sumOf { puzzle ->
puzzle.toSolve
.filter { it.segments.size in listOf(2,3,4,7) }
.size
}
}
/**
* @return
*/
fun solutionTwo(text: List<String>): Int {
val puzzles = parseText(text)
return puzzles.sumOf { puzzle ->
val map = puzzle.uniqueNumbers.groupBy { it.segments.size }
val numberOne = map[2]!!.first()
val numberSeven = map[3]!!.first()
val numberFour = map[4]!!.first()
// All of the remaining numbers have the bottom line
val fiveSegmentNumbers = map[5]!! // 2, 3, 5
val sixSegmentNumbers = map[6]!! // 0, 6, 9
// the only letter we can be 100% confident in immediately
val top = numberSeven.segments.filterNot { it in numberOne.segments }.first()
// if in 4 but not in 1 and in all of 6 segments == upper left
val topLeft = numberFour.segments
.filterNot { it in numberOne.segments }
.first { fourSegmentChar -> sixSegmentNumbers.all { it.segments.contains(fourSegmentChar) } }
// if in 1 and all of 6 segments == bottom right
val bottomRight = numberOne.segments.first { oneSegmentNumbers -> sixSegmentNumbers.all { it.segments.contains(oneSegmentNumbers) }}
// bottom right is the only other in the 1
val topRight = numberOne.segments.first { it != bottomRight }
// middle is the only remaining letter
val middle = numberFour.segments.first { it !in listOf(topLeft, topRight, bottomRight) }
// bottom is in all of the 5 segments... just filter out already used
val remainingLetters = listOf('a', 'b', 'c', 'd', 'e', 'f', 'g').filterNot {it in listOf(top, topLeft, topRight, bottomRight, middle) }
val bottom = remainingLetters.first { remainingLetter -> fiveSegmentNumbers.all { it.segments.contains(remainingLetter) } }
// bottom left is just whats left over
val bottomLeft = remainingLetters.first { it != bottom }
val one = listOf(topRight, bottomRight)
val two = listOf(top, topRight, middle, bottomLeft, bottom)
val three = listOf(top, topRight, middle, bottomRight, bottom)
val four = listOf(topLeft, middle, topRight, bottomRight)
val five = listOf(top, topLeft, middle, bottomRight, bottom)
val six = listOf(top, topLeft, middle, bottomLeft, bottomRight, bottom)
val seven = listOf(top, topRight, bottomRight)
val eight = listOf(top, topLeft, topRight, middle, bottomLeft, bottomRight, bottom)
val nine = listOf(top, topLeft, topRight, middle, bottomRight, bottom)
var fullNumber = ""
puzzle.toSolve.forEach { number ->
fullNumber += when {
number.segments.all { it in one } && number.segments.size == one.size -> "1"
number.segments.all { it in two } && number.segments.size == two.size -> "2"
number.segments.all { it in three } && number.segments.size == three.size -> "3"
number.segments.all { it in four } && number.segments.size == four.size -> "4"
number.segments.all { it in five } && number.segments.size == five.size -> "5"
number.segments.all { it in six } && number.segments.size == six.size -> "6"
number.segments.all { it in seven } && number.segments.size == seven.size -> "7"
number.segments.all { it in eight } && number.segments.size == eight.size -> "8"
number.segments.all { it in nine } && number.segments.size == nine.size -> "9"
else -> "0"
}
}
Integer.parseInt(fullNumber)
}
}
private fun parseText(text: List<String>): List<Puzzle> {
return text.map { line ->
val split = line.split("|")
val segments = split[0]
.split(" ")
.map { ClockNumber(it.toList()) }
val toSolve = split[1]
.split(" ")
.map { ClockNumber(it.toList()) }
Puzzle(
uniqueNumbers = segments,
toSolve = toSolve
)
}
}
}
fun main() {
val inputText = readInput("year_2021/day_08/Day08.txt")
val solutionOne = Day08.solutionOne(inputText)
println("Solution 1: $solutionOne")
val solutionTwo = Day08.solutionTwo(inputText)
println("Solution 2: $solutionTwo")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 5,025 | advent_of_code | Apache License 2.0 |
src/Day16.kt | fasfsfgs | 573,562,215 | false | {"Kotlin": 52546} | fun main() {
fun part1(input: List<String>): Int {
val valves = input.parseReport()
return findBestPath(valves).cumulativePressure
}
fun part2(input: List<String>): Int {
val valves = input.parseReport()
return findBestPathInPair(valves).cumulativePressure
}
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
fun findBestPathInPair(valves: List<Valve>): PathInPair {
val start = valves.find { it.name == "AA" } ?: error("start not found")
val closedValves = valves.filter { it.flow > 0 }
val firstPath = PathInPair(start, start, closedValves, 26)
val possiblePaths = mutableListOf(firstPath)
var bestPath = firstPath
while (possiblePaths.isNotEmpty()) {
val pathToWorkOn = possiblePaths.removeLast()
if (pathToWorkOn.cumulativePressure > bestPath.cumulativePressure) {
bestPath = pathToWorkOn
println(bestPath.cumulativePressure)
}
if (!isItPossibleToTopBestPathInPair(bestPath, pathToWorkOn))
continue
val nextPossiblePaths = pathToWorkOn.nextSteps(valves)
possiblePaths.addAll(nextPossiblePaths)
}
return bestPath
}
fun isItPossibleToTopBestPathInPair(bestPath: PathInPair, path: PathInPair): Boolean {
val theoreticalCumulativePressureOfClosedValves = path.valvesToOpen.asSequence()
.sortedByDescending { it.flow }
.chunked(2)
.mapIndexed { index, valves ->
if (valves.size == 1)
(path.timeLeft - ((index * 2) + 1)) * valves[0].flow
else
(path.timeLeft - ((index * 2) + 1)) * valves[0].flow + (path.timeLeft - ((index * 2) + 1)) * valves[1].flow
}
.filter { it > 0 }
.sum()
return (path.cumulativePressure + theoreticalCumulativePressureOfClosedValves) > bestPath.cumulativePressure
}
data class PathInPair(
val pos1: Valve,
val pos2: Valve,
val valvesToOpen: List<Valve>,
val timeLeft: Int,
val cumulativePressure: Int = 0,
val visitedValvesWithPressure: Map<Valve, Int> = mapOf(pos1 to cumulativePressure)
)
fun PathInPair.nextSteps(valves: List<Valve>): List<PathInPair> {
if (valvesToOpen.isEmpty() || timeLeft == 0) return listOf()
val timeLeft = timeLeft - 1
val canOpenPos1 = valvesToOpen.any { it == pos1 }
val canOpenPos2 = pos1 != pos2 && valvesToOpen.any { it == pos2 }
val newPathsNoValvesOpen = pos1.destinationIds
.flatMap { pos1Dest -> pos2.destinationIds.map { Pair(pos1Dest, it) } }
.map { Pair(valves.findByName(it.first), valves.findByName(it.second)) }
.filter { visitedValvesWithPressure[it.first] != cumulativePressure && visitedValvesWithPressure[it.second] != cumulativePressure }
.map {
copy(
pos1 = it.first, pos2 = it.second,
timeLeft = timeLeft,
visitedValvesWithPressure = visitedValvesWithPressure + (it.first to cumulativePressure) + (it.second to cumulativePressure)
)
}
if (!canOpenPos1 && !canOpenPos2 && pos1 == pos2)
return newPathsNoValvesOpen.distinctBy { setOf(it.pos1, it.pos2) }
if (!canOpenPos1 && !canOpenPos2)
return newPathsNoValvesOpen
var nextSteps = newPathsNoValvesOpen
if (canOpenPos1) {
val cumulativePressure = cumulativePressure + (pos1.flow * timeLeft)
val newPathsOnlyValvePos1Open = pos2.destinationIds
.map { valves.findByName(it) }
.map {
copy(
pos2 = it,
valvesToOpen = valvesToOpen - pos1,
timeLeft = timeLeft,
cumulativePressure = cumulativePressure,
visitedValvesWithPressure = visitedValvesWithPressure + (pos1 to cumulativePressure) + (pos2 to cumulativePressure)
)
}
nextSteps = nextSteps + newPathsOnlyValvePos1Open
}
if (canOpenPos2) {
val cumulativePressure = cumulativePressure + (pos2.flow * timeLeft)
val newPathsOnlyValvePos2Open = pos1.destinationIds
.map { valves.findByName(it) }
.map {
copy(
pos1 = it,
valvesToOpen = valvesToOpen - pos2,
timeLeft = timeLeft,
cumulativePressure = cumulativePressure,
visitedValvesWithPressure = visitedValvesWithPressure + (pos1 to cumulativePressure) + (pos2 to cumulativePressure)
)
}
nextSteps = nextSteps + newPathsOnlyValvePos2Open
}
if (canOpenPos1 && canOpenPos2) {
val cumulativePressure = cumulativePressure + (pos1.flow * timeLeft) + (pos2.flow * timeLeft)
val bothPosOpen = copy(
valvesToOpen = valvesToOpen - pos1 - pos2,
timeLeft = timeLeft,
cumulativePressure = cumulativePressure,
visitedValvesWithPressure = visitedValvesWithPressure + (pos1 to cumulativePressure) + (pos2 to cumulativePressure)
)
nextSteps = nextSteps + bothPosOpen
}
return nextSteps
}
fun findBestPath(valves: List<Valve>): Path {
val start = valves.find { it.name == "AA" } ?: error("start not found")
val closedValves = valves.filter { it.flow > 0 }
val firstPath = Path(start, closedValves, 30)
val possiblePaths = mutableListOf(firstPath)
var bestPath = firstPath
while (possiblePaths.isNotEmpty()) {
val pathToWorkOn = possiblePaths.removeLast()
if (pathToWorkOn.cumulativePressure > bestPath.cumulativePressure)
bestPath = pathToWorkOn
if (!isItPossibleToTopBestPath(bestPath, pathToWorkOn))
continue
pathToWorkOn.nextSteps(valves)
.forEach { possiblePaths.add(it) }
}
return bestPath
}
fun isItPossibleToTopBestPath(bestPath: Path, path: Path): Boolean {
val theoreticalCumulativePressureOfClosedValves = path
.valvesToOpen
.sortedByDescending { it.flow }
.mapIndexed { index, valve -> (path.timeLeft - ((index * 2) + 1)) * valve.flow }
.filter { it > 0 }
.sum()
return (path.cumulativePressure + theoreticalCumulativePressureOfClosedValves) > bestPath.cumulativePressure
}
data class Path(
val pos: Valve,
val valvesToOpen: List<Valve>,
val timeLeft: Int,
val cumulativePressure: Int = 0,
val visitedValvesWithPressure: Map<Valve, Int> = mapOf(pos to cumulativePressure)
)
fun Path.nextSteps(valves: List<Valve>): List<Path> {
if (valvesToOpen.isEmpty() || timeLeft == 0) return listOf()
val timeLeft = timeLeft - 1
val openedPath = if (valvesToOpen.contains(pos)) {
val pressure = pos.flow * timeLeft
val cumulativePressure = cumulativePressure + pressure
copy(
valvesToOpen = valvesToOpen - pos,
timeLeft = timeLeft,
cumulativePressure = cumulativePressure,
visitedValvesWithPressure = visitedValvesWithPressure + (pos to cumulativePressure)
)
} else {
null
}
val nextPaths = pos.destinationIds
.map { valves.findByName(it) }
.filter { visitedValvesWithPressure[it] != cumulativePressure }
.map {
copy(
pos = it,
timeLeft = timeLeft,
visitedValvesWithPressure = visitedValvesWithPressure + (it to cumulativePressure)
)
}
return if (openedPath != null) {
nextPaths + openedPath
} else {
nextPaths
}
}
fun List<String>.parseReport(): List<Valve> = map {
val name = it.substringAfter(' ').substringBefore(' ')
val flow = it.substringAfter('=').substringBefore(';').toInt()
val destinationIds = it.substringAfterLast("valve").substringAfter(' ').split(", ")
Valve(name, flow, destinationIds)
}
data class Valve(val name: String, val flow: Int, val destinationIds: List<String>)
fun List<Valve>.findByName(name: String): Valve = find { it.name == name } ?: error("Valve of name $name not found.")
| 0 | Kotlin | 0 | 0 | 17cfd7ff4c1c48295021213e5a53cf09607b7144 | 8,275 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day24/Day24.kt | Jessevanbekkum | 112,612,571 | false | null | package day24
import util.readLines
fun strongest(input: String): Int {
val parts = readLines(input).sorted()
.map { s -> s.split("/") }
.map { s -> s.sorted() }
.map { s -> Pair(s[0].toInt(), s[1].toInt()) }
return sum(buildStrongestBridge(parts, 0, emptyList()))
}
fun longest(input: String): Int {
val parts = readLines(input).sorted()
.map { s -> s.split("/") }
.map { s -> s.sorted() }
.map { s -> Pair(s[0].toInt(), s[1].toInt()) }
return sum(buildLongestBridge(parts, 0, emptyList()))
}
fun findMatchingPieces(blocks: List<Pair<Int, Int>>, pins: Int): List<Pair<Int, Int>> {
return blocks.filter { p -> p.first == pins || p.second == pins }
}
fun buildStrongestBridge(blocks: List<Pair<Int, Int>>, pins: Int, path: List<Pair<Int, Int>>): List<Pair<Int, Int>> {
val next = findMatchingPieces(blocks, pins)
if (next.isEmpty()) {
return path;
} else {
val options = next.map {
val nextPin = if (it.first == pins) it.second else it.first
buildLongestBridge(blocks.minus(it), nextPin, path + it)
}
return options.map { p -> Pair(p, sum(p)) }.maxBy { p -> p.second }?.first!!
}
}
fun buildLongestBridge(blocks: List<Pair<Int, Int>>, pins: Int, path: List<Pair<Int, Int>>): List<Pair<Int, Int>> {
val next = findMatchingPieces(blocks, pins)
if (next.isEmpty()) {
return path;
} else {
val options = next.map {
val nextPin = if (it.first == pins) it.second else it.first
buildLongestBridge(blocks.minus(it), nextPin, path + it)
}
val max = options.map { p -> p.size}.max()
return options.filter { p -> p.size == max }.map { p -> Pair(p, sum(p)) }.maxBy { p -> p.second }?.first!!
}
}
fun sum(path: List<Pair<Int, Int>>): Int {
return path.map { p -> p.first + p.second }.sum()
} | 0 | Kotlin | 0 | 0 | 1340efd354c61cd070c621cdf1eadecfc23a7cc5 | 1,946 | aoc-2017 | Apache License 2.0 |
src/Day12.kt | juliantoledo | 570,579,626 | false | {"Kotlin": 34375} | import java.util.*
fun main() {
data class DistancePair(
val location: Pair<Int,Int>,
val distance: Int
)
class DistanceComparator : Comparator<DistancePair> {
override fun compare(first:DistancePair, second: DistancePair): Int {
return first.distance.compareTo(second.distance)
}
}
fun nextNodes(matrix: MutableList<List<Int>>, node: Pair<Int,Int>): List<Pair<Int, Int>> {
var nodes = arrayListOf<Pair<Int,Int>>()
val x = node.first
val y = node.second
if (y > 0 && matrix[x][y-1] - matrix[x][y] <= 1)
nodes.add(Pair(x, y-1))
if (y < matrix[x].lastIndex && matrix[x][y+1] - matrix[x][y] <= 1)
nodes.add(Pair(x, y+1))
if (x > 0 && matrix[x-1][y] - matrix[x][y] <= 1)
nodes.add(Pair(x-1, y))
if (x < matrix.lastIndex && matrix[x+1][y] - matrix[x][y] <= 1)
nodes.add(Pair(x+1, y))
return nodes
}
fun dijkstra(start: Pair<Int, Int>, end: Pair<Int, Int>, matrix: MutableList<List<Int>>): Int {
val queue = PriorityQueue(DistanceComparator())
val visited = hashSetOf<Pair<Int,Int>>()
queue.add(DistancePair(start, 1))
while (queue.isNotEmpty()){
val node = queue.poll()
if (visited.contains(node.location)) continue
visited.add(node.location)
val neighbors = nextNodes(matrix, node.location)
if (neighbors.any { it == end }) return node.distance
neighbors.forEach{ adj ->
if (!visited.contains(adj)) queue.add(DistancePair(adj, node.distance + 1))
}
}
return -1
}
fun solve(input: List<String>): Int {
var destination = Pair(0,0)
var start = Pair(0,0)
var matrix = mutableListOf<List<Int>>()
input.forEachIndexed { index, chars ->
val row = chars.mapIndexed { index2, char ->
when (char) {
'S' -> {start = Pair(index, index2); 'a'.code - 97}
'E' -> {destination = Pair(index, index2); 'z'.code - 97}
else -> char.code - 97
}
}
matrix.add(row)
}
var total = dijkstra(start, destination, matrix)
println(total)
// Part 2
var startingNodes: MutableList<Pair<Int, Int>> = mutableListOf()
matrix.forEachIndexed { x, row ->
row.forEachIndexed { y, node ->
if (node == 0) startingNodes.add(Pair(x,y))
}
}
var partTwo = Int.MAX_VALUE
startingNodes.forEach { node ->
var total = dijkstra(node, destination, matrix)
if (total != -1 && partTwo > total) partTwo = total
}
println("Part2: $partTwo")
return total
}
var test = solve(readInput("Day12_test"))
println("Test1: $test")
check(test == 31)
var first = solve(readInput("Day12_input"))
println("Part1: $first")
}
| 0 | Kotlin | 0 | 0 | 0b9af1c79b4ef14c64e9a949508af53358335f43 | 3,049 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day12.kt | ShuffleZZZ | 572,630,279 | false | {"Kotlin": 29686} | var start = 0 to 0
var end = 0 to 0
private fun heights(input: List<String>) =
input.mapIndexed { i, line ->
line.mapIndexed { j, char ->
when (char) {
'S' -> 'a'.also { start = i to j }
'E' -> 'z'.also { end = i to j }
else -> char
} - 'a'
}
}
private fun dijkstra(heights: List<List<Int>>, start: Pair<Int, Int>): List<List<Int>> {
val distances = List(heights.size) { MutableList(heights.first().size) { Int.MAX_VALUE } }
val unvisited = distances.indexPairs().toMutableSet()
distances[start] = 0
var cur = start
while (true) {
unvisited.remove(cur)
neighbours(cur).filter { (i, j) -> i in distances.indices && j in distances.first().indices }
.filter { unvisited.contains(it) }.forEach {
if (heights[it] <= heights[cur] + 1) {
distances[it] = distances[it].coerceAtMost(distances[cur] + 1)
}
}
val next = unvisited.minByOrNull { distances[it] }
if (next == null || distances[next] == Int.MAX_VALUE) break
cur = next
}
return distances
}
fun main() {
fun part1(input: List<String>) = dijkstra(heights(input), start)[end]
fun part2(input: List<String>): Int {
val heights = heights(input)
return heights.indexPairs { it == 0 }.minOf { dijkstra(heights, it)[end] }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e | 1,723 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/days/y2023/day02/Day02.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2023.day02
import util.InputReader
fun partOne(input: String): Int {
val parsed = parseInput(input)
// The Elf would first like to know which games would have been possible if the bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes?
val possible = parsed.filter { it.possible(12, 13, 14) }
return possible.sumOf { it.id }
}
fun partTwo(input: String): Int {
val parsed = parseInput(input)
return parsed
.map { game -> game.minPossible() }
.sumOf { set -> set.product() }
}
private fun GameSet.product() = countBlue * countGreen * countRed
private fun Game.possible(red: Int, green: Int, blue: Int): Boolean {
return sets.all { set ->
set.countRed <= red && set.countGreen <= green && set.countBlue <= blue
}
}
private fun Game.minPossible(): GameSet {
val red = sets.maxOf { it.countRed }
val green = sets.maxOf { it.countGreen }
val blue = sets.maxOf { it.countBlue }
return GameSet(countRed = red, countGreen = green, countBlue = blue)
}
private fun parseInput(input: String): List<Game> {
return input.lines().filter { it.isNotEmpty() }.map { line -> Game.from(line) }
}
private data class Game(val line: String, val id: Int, val sets: List<GameSet>) {
companion object {
fun from(line: String): Game {
val match = Regex("Game (?<id>\\d+): (?<sets>.*)").find(line)?.groups ?: error("Did not match: $line")
val id = match.getInt("id")
val sets = match.getString("sets").split("; ").map { set -> GameSet.from(set) }
return Game(line, id, sets)
}
}
}
private data class GameSet(val countBlue: Int, val countRed: Int, val countGreen: Int) {
companion object {
fun from(line: String): GameSet {
val chunks = line.split(", ")
val countBlue = chunks.blueChunk()
val countRed = chunks.redChunk()
val countGreen = chunks.greenChunk()
return GameSet(countBlue ?: 0, countRed ?: 0, countGreen ?: 0)
}
}
}
private fun List<String>.blueChunk(): Int? =
firstNotNullOfOrNull { Regex("(?<countBlue>\\d+) blue").find(it)?.groups }?.getInt("countBlue")
private fun List<String>.redChunk(): Int? =
firstNotNullOfOrNull { Regex("(?<countRed>\\d+) red").find(it)?.groups }?.getInt("countRed")
private fun List<String>.greenChunk(): Int? =
firstNotNullOfOrNull { Regex("(?<countGreen>\\d+) green").find(it)?.groups }?.getInt("countGreen")
private fun MatchGroupCollection.getInt(name: String) = this[name]?.value?.toInt() ?: error(name)
private fun MatchGroupCollection.getString(name: String) = this[name]?.value ?: error(name)
fun main() {
println("Example One: ${partOne(InputReader.getExample(2023, 2))}")
println("Part One: ${partOne(InputReader.getPuzzle(2023, 2))}")
println("Part Two: ${partTwo(InputReader.getPuzzle(2023, 2))}")
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 2,922 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/aoc2023/Day07.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import utils.InputUtils
enum class HandTypes {
FIVE_KIND, FOUR_KIND, FULL_HOUSE, THREE_KIND, TWO_PAIR, ONE_PAIR, HIGH_CARD
}
val scores = "23456789TJQKA".mapIndexed { index, c -> c to index }.toMap()
val jScore = scores['J']!!
fun typeForHand(cards: String): HandTypes {
val counts = cards.groupingBy { it }.eachCount().values.sortedDescending()
if (counts[0] == 5) { return HandTypes.FIVE_KIND }
val (c1, c2) = counts
return if (c1 == 4) { HandTypes.FOUR_KIND }
else if (c1 == 3 && c2 == 2) { HandTypes.FULL_HOUSE }
else if (c1 == 3) { HandTypes.THREE_KIND }
else if (c1 == 2 && c2 == 2) { HandTypes.TWO_PAIR }
else if (c1 == 2) { HandTypes.ONE_PAIR }
else HandTypes.HIGH_CARD
}
fun wildTypeForHand(cards: String): HandTypes {
val counts = cards.groupingBy { it }.eachCount()
val jCount = counts['J'] ?: 0
return if (jCount in 1..4) {
val highest = (counts - 'J').entries.maxByOrNull { it.value }!!.key
typeForHand(cards.replace('J', highest))
} else {
typeForHand(cards)
}
}
fun String.asListOfScores() = map { scores[it]!! }
fun sortHands(a: String, b: String) = a.asListOfScores().zip(b.asListOfScores()).map { compareValues(it.first, it.second) }.first { it != 0 }
class Hand(val cards: String, val bid: Long): Comparable<Hand> {
val type = typeForHand(cards)
val sortScore = cards.asListOfScores()
.fold(0) { acc, x -> (acc * 16) + x}
override fun compareTo(other: Hand): Int = (compareByDescending<Hand> { it.type }.thenBy { it.sortScore }).compare(this, other)
override fun toString(): String {
return "Hand(cards='$cards', bid=$bid, type=$type)"
}
}
class Hand2(val cards: String, val bid: Long): Comparable<Hand2> {
val type = wildTypeForHand(cards)
val sortScore = cards.asListOfScores()
.map { if (it == jScore) { 0 } else { it + 1 } }
.fold(0) { acc, x -> (acc * 16) + x}
override fun compareTo(other: Hand2): Int = (compareByDescending<Hand2> { it.type }.thenBy { it.sortScore }).compare(this, other)
override fun toString(): String {
return "Hand(cards='$cards', bid=$bid, type=$type)"
}
}
fun main() {
val testInput = """32T3K 765
T55J5 684
KK677 28
KTJJT 220
QQQJA 483""".trimIndent().split("\n")
fun part1(input: List<String>): Long {
val hands = input.map { Hand(it.substringBefore(' '), it.substringAfter(' ').toLong()) }
return hands
.sorted()
.mapIndexed { index, hand -> index + 1 to hand.bid }
.onEach { println(it) }
.sumOf { it.first * it.second }
}
fun part2(input: List<String>): Long {
val hands = input.map { Hand2(it.substringBefore(' '), it.substringAfter(' ').toLong()) }
return hands
.sorted()
.mapIndexed { index, hand -> index + 1 to hand.bid }
.onEach { println(it) }
.sumOf { it.first * it.second }
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 6440L)
println(part2(testInput))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 7)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 3,343 | aoc-2022-kotlin | Apache License 2.0 |
src/com/ncorti/aoc2023/Day19.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
fun main() {
fun parseInput(): Pair<Map<String, List<String>>, List<Map<String, Int>>> {
val (workflows, parts) = getInputAsText("19") {
split("\n\n").filter(String::isNotBlank).map {
it.split("\n").filter(String::isNotBlank)
}
}
val workflowMap = workflows.associate {
val key = it.substringBefore("{").trim()
val value = it.substringBefore("}").substringAfter("{").split(",")
key to value
}
val partsList = parts.map {
it.removeSurrounding("{", "}").split(",").map {
it.split("=")
}.associate { (key, value) ->
key to value.toInt()
}
}
return workflowMap to partsList
}
fun computeNewIntervals(
greaterThan: Boolean, threshold: Int, letter: String, target: String, input: IntRange
): Pair<IntRange, IntRange> = when {
target != letter -> input to input
greaterThan -> (threshold + 1)..input.last to input.first..threshold
else -> input.first..<threshold to (threshold)..input.last
}
fun IntRange.size(): Long = (this.last - this.first + 1).toLong()
fun computeCombination(
workflows: Map<String, List<String>>,
current: List<String>,
idx: Int,
rangeX: IntRange,
rangeM: IntRange,
rangeA: IntRange,
rangeS: IntRange
): Long {
val step = current[idx]
return when {
"<" in step || ">" in step -> {
val (condition, consequence) = step.split(":")
val letter = condition.substringBefore(">").substringBefore("<")
val threshold = condition.substringAfter(">").substringAfter("<").toInt()
val greaterThan = ">" in condition
val (newX, oldX) = computeNewIntervals(greaterThan, threshold, letter, "x", rangeX)
val (newM, oldM) = computeNewIntervals(greaterThan, threshold, letter, "m", rangeM)
val (newA, oldA) = computeNewIntervals(greaterThan, threshold, letter, "a", rangeA)
val (newS, oldS) = computeNewIntervals(greaterThan, threshold, letter, "s", rangeS)
val newCombinationResult = when {
"R" in consequence -> 0
"A" in consequence -> newX.size() * newM.size() * newA.size() * newS.size()
else -> computeCombination(workflows, workflows[consequence]!!, 0, newX, newM, newA, newS)
}
newCombinationResult + computeCombination(workflows, current, idx + 1, oldX, oldM, oldA, oldS)
}
"A" in step -> rangeX.size() * rangeM.size() * rangeA.size() * rangeS.size()
"R" in step -> 0
else -> computeCombination(workflows, workflows[step]!!, 0, rangeX, rangeM, rangeA, rangeS)
}
}
fun part1(): Int {
val (workflows, parts) = parseInput()
return parts.sumOf { map ->
var currentWorkflow = workflows["in"]!!
var idx = 0
var accepted = false
while (true) {
val step = currentWorkflow[idx]
val (condition, consequence) = if (":" in step) {
step.split(":")
} else {
listOf("", step)
}
val letter = condition.substringBefore(">").substringBefore("<")
val threshold = condition.substringAfter(">").substringAfter("<")
if ((">" !in condition && "<" !in condition) || (">" in condition && map[letter]!! > threshold.toInt()) || ("<" in condition && map[letter]!! < threshold.toInt())) {
if (consequence == "A") {
accepted = true
break
} else if (consequence == "R") {
accepted = false
break
}
currentWorkflow = workflows[consequence]!!
idx = 0
continue
}
idx++
}
if (accepted) {
map["x"]!! + map["m"]!! + map["a"]!! + map["s"]!!
} else {
0
}
}
}
fun part2(): Long {
val (workflows, _) = parseInput()
return computeCombination(
workflows = workflows,
current = workflows["in"]!!,
idx = 0,
rangeX = 1..4000,
rangeM = 1..4000,
rangeA = 1..4000,
rangeS = 1..4000
)
}
println(part1())
println(part2())
}
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 4,742 | adventofcode-2023 | MIT License |
src/main/kotlin/com/colinodell/advent2023/Day19.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day19(input: String) {
private val workflows = parseWorkflows(input)
private val parts = parseParts(input)
private class Rule(val category: Char, op: Char, n: Int, val dest: String) {
val range = when (op) {
'<' -> 1 until n
'>' -> n + 1..4000
else -> throw IllegalArgumentException("Invalid operator: $op")
}
fun apply(part: Map<Char, Int>) = part[category] in range
}
private class Workflow(private val rules: List<Rule>, private val default: String) {
fun next(part: Map<Char, Int>) = rules.firstOrNull { it.apply(part) }?.dest ?: default
// Returns which workflows can run next, and the filtered ranges that should be passed to them
fun next(c: Combinations): List<Pair<String, Combinations>> {
var remainder = c.copy()
val next = rules.map { rule ->
Pair(rule.dest, remainder.intersect(rule.category, rule.range)).also { remainder = remainder.subtract(rule.category, rule.range) }
}
// Also include the default (for whatever is left)
return next.toMutableList().apply {
add(default to remainder)
}
}
}
private data class Combinations(private val ranges: Map<Char, Collection<IntRange>>) {
val count get() = ranges.values.productOf { it.sumOf { it.size.toLong() } }
fun intersect(category: Char, range: IntRange) = Combinations(ranges.toMutableMap().also { it[category] = it[category]!!.intersect(range) })
fun subtract(category: Char, range: IntRange) = Combinations(ranges.toMutableMap().also { it[category] = it[category]!!.subtract(range) })
}
private tailrec fun accepted(part: Map<Char, Int>, workflowId: String): Boolean {
return when (workflowId) {
"A" -> true
"R" -> false
else -> accepted(part, workflows[workflowId]!!.next(part))
}
}
private fun calculateAcceptedCombinations(workflowId: String, combinations: Combinations): Long =
workflows[workflowId]!!.next(combinations)
.sumOf { (nextWorkflowId, allowedCombos) ->
when (nextWorkflowId) {
"A" -> allowedCombos.count
"R" -> 0
else -> calculateAcceptedCombinations(nextWorkflowId, allowedCombos)
}
}
fun solvePart1() = parts.filter { accepted(it, "in") }.sumOf { it.values.sum() }
fun solvePart2() = calculateAcceptedCombinations("in", Combinations("xmas".associateWith { listOf(1..4000) }))
private fun parseWorkflows(input: String) = input
.split("\n\n")
.first()
.split("\n").associate { line ->
val id = line.takeWhile { it != '{' }
val rules = line.split('{').last().trimEnd('}').split(",")
id to Workflow(
rules.dropLast(1).map { rule ->
val (category, op, n, dest) = Regex("""(\w)([<>])(\d+):(\w+)""").matchEntire(rule)!!.destructured
Rule(category[0], op[0], n.toInt(), dest)
},
rules.last()
)
}
private fun parseParts(input: String) = input
.split("\n\n")
.last()
.split("\n")
.map { line ->
// Example: {x=787,m=2655,a=1222,s=2876}
line.drop(1).dropLast(1).split(",").associate { part ->
val (k, v) = part.split("=")
k[0] to v.toInt()
}
}
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 3,604 | advent-2023 | MIT License |
day16/Part2.kt | anthaas | 317,622,929 | false | null | import java.io.File
fun main(args: Array<String>) {
val input = File("input.txt").bufferedReader().use { it.readText() }.split("\n\n")
val rules = input[0].split("\n").map {
it.split(":")[1].split(" or ")
.map { it.split('-').let { (low, high) -> low.trim().toInt() to high.trim().toInt() } }
}
val myTicket = input[1].split("\n")[1].split(",").map { it.toLong() }
val nearbyTickets =
input[2].split("\n").subList(1, input[2].split("\n").size).map { it.split(",").map { it.toInt() } }
val filteredNearbyTickets =
nearbyTickets.filter { checkIfAnyRuleNotValid(it, rules) }
val columns =
(0 until filteredNearbyTickets[0].size).map { i -> filteredNearbyTickets.map { it[i] }.toList() }.toList()
val rulesCanBeAppliedToColumns = (0 until rules.size).map { ruleIndex ->
ruleIndex to columns.mapIndexed { index, list -> if (checkIfOneRule(list, rules[ruleIndex])) index else -1 }
.filter { it != -1 }.toMutableList()
}.toMutableList()
val exactOneRule = mutableListOf<Pair<Int, List<Int>>>()
while (rulesCanBeAppliedToColumns.isNotEmpty()) {
exactOneRule.addAll(rulesCanBeAppliedToColumns.filter { it.second.size == 1 })
exactOneRule.forEach { if (it in rulesCanBeAppliedToColumns) rulesCanBeAppliedToColumns.remove(it) }
rulesCanBeAppliedToColumns.map { rule ->
exactOneRule.forEach {
if (it.second[0] in rule.second) rule.second.remove(
it.second[0]
)
}
}
}
val sorted = exactOneRule.sortedBy { it.first }.map { it.first to it.second[0] }
val result = (0 until 6).map { myTicket[sorted[it].second] }
println(result.reduce { acc, i -> acc * i })
}
private fun checkIfAnyRuleNotValid(input: List<Int>, rules: List<List<Pair<Int, Int>>>): Boolean {
return input.map { value -> rules.map { it.map { value in it.first..it.second }.any { it } }.any { it } }.all { it }
}
private fun checkIfOneRule(input: List<Int>, rule: List<Pair<Int, Int>>): Boolean {
return input.map { value -> rule.map { value in it.first..it.second }.any { it } }.all { it }
}
| 0 | Kotlin | 0 | 0 | aba452e0f6dd207e34d17b29e2c91ee21c1f3e41 | 2,190 | Advent-of-Code-2020 | MIT License |
src/main/kotlin/codes/jakob/aoc/solution/Day08.kt | The-Self-Taught-Software-Engineer | 433,875,929 | false | {"Kotlin": 56277} | package codes.jakob.aoc.solution
import codes.jakob.aoc.solution.Day08.Digit.*
object Day08 : Solution() {
override fun solvePart1(input: String): Any {
val wantedDigits: Set<Digit> = setOf(ONE, FOUR, SEVEN, EIGHT)
return parseInput(input).sumOf { entry: Entry ->
val mappings: Map<Pattern, Digit> = processEntry(entry.inputs).reversed()
return@sumOf entry.outputs.map { mappings[it]!! }.count { it in wantedDigits }
}
}
override fun solvePart2(input: String): Any {
return parseInput(input).sumOf { entry: Entry ->
val mappings: Map<Pattern, Digit> = processEntry(entry.inputs).reversed()
return@sumOf entry.outputs.map { mappings[it]!!.value }.joinToString("").toInt()
}
}
private fun processEntry(patterns: List<Pattern>): Map<Digit, Pattern> {
val mappings: MutableMap<Digit, Pattern> = mutableMapOf()
for (inputPattern: Pattern in patterns) {
val digit: Digit = when (inputPattern.segments.count()) {
2 -> ONE
3 -> SEVEN
4 -> FOUR
7 -> EIGHT
else -> continue
}
mappings[digit] = inputPattern
}
for (inputPattern: Pattern in patterns.filterNot { it in mappings.values }) {
val digit: Digit = values().first { inputPattern.isIt(it, mappings) }
mappings[digit] = inputPattern
}
return mappings
}
private fun parseInput(input: String): List<Entry> {
return input.splitMultiline().map { entry ->
val (inputs: String, outputs: String) = entry.split(" | ")
return@map Entry(parseSignals(inputs), parseSignals(outputs))
}
}
private fun parseSignals(signals: String): List<Pattern> {
return signals
.split(" ")
.filter { it.isNotBlank() }
.map { signal ->
signal
.split("")
.filter { it.isNotBlank() }
.map { it.toSingleChar() }
.let { Pattern.fromSymbols(it) }
}
}
data class Entry(
val inputs: List<Pattern>,
val outputs: List<Pattern>,
)
data class Pattern(
val segments: Set<Segment>,
) {
constructor(segments: Collection<Segment>) : this(segments.toSet())
fun isIt(digit: Digit, mappings: Map<Digit, Pattern>): Boolean {
return when (digit) {
ZERO -> count() == 6 && !isIt(SIX, mappings) && !isIt(NINE, mappings)
ONE -> count() == 2
TWO -> count() == 5 && !isIt(THREE, mappings) && !isIt(FIVE, mappings)
THREE -> count() == 5 && intersect(mappings[ONE]!!).count() == 2
FOUR -> count() == 4
FIVE -> count() == 5 && !isIt(THREE, mappings) && intersect(mappings[FOUR]!!).count() == 3
SIX -> count() == 6 && intersect(mappings[SEVEN]!!).count() == 2
SEVEN -> count() == 3
EIGHT -> count() == 7
NINE -> count() == 6 && intersect(mappings[FOUR]!!).count() == 4
}
}
private fun count(): Int = this.segments.count()
private fun intersect(other: Pattern): Set<Segment> {
return this.segments.intersect(other.segments)
}
companion object {
fun fromSymbols(symbols: Collection<Char>): Pattern {
return Pattern(symbols.map { Segment.fromSymbol(it) ?: error("No Segment exists for symbol: $it") })
}
}
}
enum class Digit(val value: Int) {
ZERO(0),
ONE(1),
TWO(2),
THREE(3),
FOUR(4),
FIVE(5),
SIX(6),
SEVEN(7),
EIGHT(8),
NINE(9);
}
enum class Segment(val symbol: Char) {
A('a'),
B('b'),
C('c'),
D('d'),
E('e'),
F('f'),
G('g');
companion object {
fun fromSymbol(symbol: Char): Segment? {
return values().find { it.symbol == symbol }
}
}
}
}
fun main() {
Day08.solve()
}
| 0 | Kotlin | 0 | 6 | d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c | 4,239 | advent-of-code-2021 | MIT License |
src/main/kotlin/be/twofold/aoc2021/Day08.kt | jandk | 433,510,612 | false | {"Kotlin": 10227} | package be.twofold.aoc2021
object Day08 {
fun part1(input: List<String>): Int {
return input
.map { it.split('|').let { it[1] } }
.flatMap { it.split(' ') }
.count { it.length in listOf(2, 3, 4, 7) }
}
fun part2(input: List<String>): Int {
return input.sumOf { decode(it) }
}
private fun decode(s: String): Int {
val split = s.split('|').map { it.trim() }
val patterns = split[0].split(' ').map { it.toSet() }
val one = patterns.single { it.size == 2 }
val four = patterns.single { it.size == 4 }
val seven = patterns.single { it.size == 3 }
val eight = patterns.single { it.size == 7 }
val fourDiff = four - one
val three = patterns.single { it.size == 5 && it.containsAll(one) }
val five = patterns.single { it.size == 5 && it.containsAll(fourDiff) }
val two = patterns.single { it.size == 5 && it != three && it != five }
val nine = patterns.single { it.size == 6 && it.containsAll(four) }
val six = patterns.single { it.size == 6 && it != nine && it.containsAll(fourDiff) }
val zero = patterns.single { it.size == 6 && it != nine && it != six }
val numbers = mapOf(
zero to 0, one to 1, two to 2, three to 3, four to 4,
five to 5, six to 6, seven to 7, eight to 8, nine to 9
)
return split[1]
.split(' ')
.map { numbers[it.toSet()]!! }
.reduce { a, i -> a * 10 + i }
}
}
fun main() {
val input = Util.readFile("/day08.txt")
println("Part 1: ${Day08.part1(input)}")
println("Part 2: ${Day08.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 2408fb594d6ce7eeb2098bc2e38d8fa2b90f39c3 | 1,698 | aoc2021 | MIT License |
src/Day08.kt | djleeds | 572,720,298 | false | {"Kotlin": 43505} | @JvmInline value class Tree(val height: Int)
class Forest(private val width: Int, private val height: Int) {
private val trees: Array<Array<Tree?>> = Array(width) { Array(height) { null } }
fun addTree(x: Int, y: Int, height: Int) {
trees[x][y] = Tree(height)
}
fun coordinates() = Iterable {
iterator { (0 until height).forEach { y -> (0 until width).forEach { x -> yield(Coordinates8(x, y)) } } }
}
fun isVisible(coordinates: Coordinates8) = Direction.values().any { isVisible(coordinates, it) }
fun scenicScore(coordinates: Coordinates8) = Direction.values().map { scenicScore(coordinates, it) }.fold(1) { acc, it -> acc * it }
private operator fun Array<Array<Tree?>>.get(coordinates: Coordinates8): Tree? =
runCatching { this[coordinates.x][coordinates.y] }.getOrNull()
private fun isVisible(coordinates: Coordinates8, direction: Direction): Boolean {
val height = trees[coordinates]!!.height
return treeLine(coordinates, direction).firstOrNull { it.height >= height } == null
}
private fun scenicScore(coordinates: Coordinates8, direction: Direction): Int {
val height = trees[coordinates]!!.height
val treeLine = treeLine(coordinates, direction)
return treeLine.indexOfFirst { it.height >= height }.takeIf { it != -1 }?.plus(1) ?: treeLine.count()
}
private fun treeLine(coordinates: Coordinates8, direction: Direction) = Iterable {
iterator {
var coords = coordinates.step(direction)
while (coords.x in 0 until width && coords.y in 0 until height) {
trees[coords]?.let { tree -> yield(tree); coords = coords.step(direction) }
}
}
}
}
data class Coordinates8(val x: Int, val y: Int) {
fun step(direction: Direction) = when (direction) {
Direction.NORTH -> copy(y = y - 1)
Direction.SOUTH -> copy(y = y + 1)
Direction.EAST -> copy(x = x + 1)
Direction.WEST -> copy(x = x - 1)
}
}
enum class Direction { NORTH, SOUTH, EAST, WEST }
private fun parse(input: List<String>) =
Forest(input.first().length, input.size).apply {
input.forEachIndexed { y, row ->
row.forEachIndexed { x, height ->
addTree(x, y, height.toString().toInt())
}
}
}
fun main() {
fun part1(forest: Forest): Int = forest.coordinates().count(forest::isVisible)
fun part2(forest: Forest): Int = forest.coordinates().maxOf(forest::scenicScore)
var forest = parse(readInput("Day08_test"))
check(part1(forest) == 21)
check(part2(forest) == 8)
forest = parse(readInput("Day08"))
println(part1(forest))
println(part2(forest))
}
| 0 | Kotlin | 0 | 4 | 98946a517c5ab8cbb337439565f9eb35e0ce1c72 | 2,733 | advent-of-code-in-kotlin-2022 | Apache License 2.0 |
src/day15/Day15.kt | maxmil | 578,287,889 | false | {"Kotlin": 32792} | package day15
import println
import readInput
import java.util.Comparator
import java.util.PriorityQueue
import kotlin.system.measureTimeMillis
data class Point(val x: Int, val y: Int)
data class Node(val point: Point, val risk: Int, val distance: Int)
private fun List<String>.parse(tiles: Int, width: Int, height: Int) = (0..24).flatMap { tile ->
val tileX = tile % tiles * width
val tileY = tile / tiles * height
flatMapIndexed { y, row ->
row.mapIndexed { x, s ->
val risk = ((s.toString().toInt() + tile % tiles + tile / tiles)).let { if (it > 9) it % 9 else it }
val shortestPath = if (tileX + x == 0 && tileY + y == 0) 0 else Int.MAX_VALUE
Node(Point(tileX + x, tileY + y), risk, shortestPath)
}
}
}.associateBy { it.point }
private fun findPathWithLowestRisk(input: List<String>, tiles: Int): Int {
val height = input.size
val width = input[0].length
val maxY = height * tiles - 1
val maxX = width * tiles - 1
val grid = input.parse(tiles, width, height).toMutableMap()
val queue = PriorityQueue<Node>(Comparator.comparing { node -> node.distance })
val visited = mutableSetOf<Node>()
queue.add(grid[Point(0, 0)]!!)
while (queue.isNotEmpty()) {
val node = queue.poll()
arrayListOf(Point(-1, 0), Point(1, 0), Point(0, -1), Point(0, 1))
.map { Point(it.x + node.point.x, it.y + node.point.y) }
.forEach {
grid[it]?.apply {
if (!visited.contains(this) && this.distance > node.distance + risk) {
val newNode = copy(distance = node.distance + risk)
queue.remove(this)
queue.add(newNode)
grid[this.point] = newNode
}
}
}
visited.add(node)
}
return grid[Point(maxX, maxY)]!!.distance
}
fun part1(input: List<String>): Int {
return findPathWithLowestRisk(input, 1)
}
fun part2(input: List<String>): Int {
return findPathWithLowestRisk(input, 5)
}
fun main() {
val testInput = readInput("day15/input_test")
check(part1(testInput) == 40)
check(part2(testInput) == 315)
val input = readInput("day15/input")
part1(input).println()
measureTimeMillis { print(part2(input)) }.apply { println(" in $this ms") }
}
| 0 | Kotlin | 0 | 0 | 246353788b1259ba11321d2b8079c044af2e211a | 2,386 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/net/mguenther/adventofcode/day21/Day21.kt | mguenther | 115,937,032 | false | null | package net.mguenther.adventofcode.day21
import kotlin.math.sqrt
/**
* @author <NAME> (<EMAIL>)
*/
data class Pattern(val grid: List<List<Char>>) {
constructor(input: String) : this(input.split("/").map { it.toList() })
private fun flip(): Pattern = Pattern(grid.map { it.reversed() })
private fun rotate(): Pattern =
Pattern(
(0 until grid.size).map { row ->
(0 until grid.size).map { column ->
grid[grid.size - 1 - column][row]
}
}
)
fun isoforms(): List<Pattern> {
val rotations = (0 until 3).fold(listOf(this)) { acc, _ -> acc + acc.last().rotate() }
val flips = rotations.map { it.flip() }
return rotations + flips
}
fun split(): List<Pattern> {
if (grid.size == 2 || grid.size == 3) return listOf(this)
else {
val sizeOfSegment = when {
grid.size % 2 == 0 -> 2
else -> 3
}
return split(sizeOfSegment)
}
}
private fun split(sizeOfSegment: Int): List<Pattern> =
(0 until grid.size / sizeOfSegment).flatMap { rowSegment ->
(0 until grid.size / sizeOfSegment).map { colSegment ->
Pattern(
(0 until sizeOfSegment).map { rowInSegment ->
(0 until sizeOfSegment).map { colInSegment ->
grid[rowSegment * sizeOfSegment + rowInSegment][colSegment * sizeOfSegment + colInSegment]
}
})
}
}
private fun nextTo(that: Pattern): Pattern = Pattern(grid.mapIndexed { i, row -> row + that.grid[i] })
private fun over(that: Pattern): Pattern = Pattern(grid + that.grid)
companion object {
fun combine(patterns: List<Pattern>): Pattern {
if (patterns.size == 1) {
return patterns.get(0)
} else {
val chunks = sqrt(patterns.size.toFloat()).toInt()
return patterns
.chunked(chunks).map { it.reduce { l, r -> l.nextTo(r) } }
.chunked(chunks).map { it.reduce { l, r -> l.over(r) } }
.first()
}
}
}
override fun toString(): String {
return grid.joinToString("/") { it.joinToString("") }
}
}
fun solve(rules: Map<Pattern, Pattern>, initial: Pattern = Pattern(".#./..#/###"), iterations: Int = 4) {
var pattern: Pattern = initial.split().map { rules[it] }.get(0)!!
repeat(iterations) {
val newPatterns = pattern.split().map { rules[it]!! }
pattern = Pattern.combine(newPatterns)
}
println(pattern.toString().count { c -> c == '#' })
}
fun readRules(resourceFile: String): Map<Pattern, Pattern> {
return Thread::class.java.getResource(resourceFile)
.readText()
.split("\n")
.map { toPatterns(it) }
.reduceRight { l, r -> l + r }
}
private fun toPatterns(line: String): Map<Pattern, Pattern> {
val tokens = line.split(" => ")
val ruleBlueprint = Pattern(tokens[0])
val replacement = Pattern(tokens[1])
return ruleBlueprint.isoforms().map { Pair(it, replacement) }.toMap()
}
| 0 | Kotlin | 0 | 0 | c2f80c7edc81a4927b0537ca6b6a156cabb905ba | 3,422 | advent-of-code-2017 | MIT License |
src/Day02.kt | Reivax47 | 572,984,467 | false | {"Kotlin": 32685} | fun main() {
val winner = mapOf("A" to "Y", "B" to "Z", "C" to "X")
val loser = mapOf("A" to "Z", "B" to "X", "C" to "Y")
val equal = mapOf("A" to "X", "B" to "Y", "C" to "Z")
fun point_lie_a_mon_jeu(input: List<String>): Int {
val somme = input.sumOf {
it.substring(2, 3)
.first().code - 87
}
return somme;
}
fun point_lie_a_mes_victoires(input: List<String>): Int {
var somme = 0
input.forEach { ligne ->
val tirage = ligne.split(" ")
somme += if (tirage[0] == "A" && tirage[1] == "X"
|| tirage[0] == "B" && tirage[1] == "Y"
|| tirage[0] == "C" && tirage[1] == "Z"
) 3 else
if (tirage[0] == "A" && tirage[1] == "Y"
|| tirage[0] == "B" && tirage[1] == "Z"
|| tirage[0] == "C" && tirage[1] == "X"
) 6 else 0
}
return somme
}
fun part1(input: List<String>): Int {
val somme_my_game = point_lie_a_mon_jeu(input)
val somme_my_win = point_lie_a_mes_victoires(input)
return somme_my_game + somme_my_win
}
fun part2(input: List<String>): Int {
val transform = input.map { ligne ->
if (ligne.substring(2, 3) == "X") ligne.substring(0, 1) + " " + loser[ligne.substring(0, 1)]
else if (ligne.substring(2, 3) == "Y") ligne.substring(0, 1) + " " + equal[ligne.substring(0, 1)]
else ligne.substring(0, 1) + " " + winner[ligne.substring(
0,
1
)]
}
return part1(transform)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0affd02997046d72f15d493a148f99f58f3b2fb9 | 1,948 | AD2022-01 | Apache License 2.0 |
src/year2022/day12/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2022.day12
import readInput
fun main() {
val day = "12"
val expectedTest1 = 31
val expectedTest2 = 29
fun getPosition(input: List<CharSequence>, positionToFind: Char) =
input.mapIndexed { index, charSequence -> charSequence.indexOf(positionToFind) to index }.first { it.first > -1 }
fun getPositions(input: List<CharSequence>, positionToFind: Char) =
input.mapIndexed { index, charSequence -> charSequence.indexOf(positionToFind) to index }.filter { it.first > -1 }.toSet()
fun availableMoves(position: Pair<Int, Int>, map: List<List<Int>>, start: Pair<Int, Int>, end: Pair<Int, Int>): Sequence<Pair<Int, Int>> {
val sequenceOf = sequenceOf(
position.first + 1 to position.second,
position.first - 1 to position.second,
position.first to position.second + 1,
position.first to position.second - 1,
)
return sequenceOf.filter { it.first >= 0 && it.second >= 0 && it.first < map[0].size && it.second < map.size }
.filter { ((map[position.second][position.first] - map[it.second][it.first]) <= 1) }
}
fun getMap(input: List<CharSequence>) = input.map { line ->
line.map {
when (it) {
'S' -> 0
'E' -> 'z' - 'a'
else -> it - 'a'
}
}
}
fun searchIt(input: List<CharSequence>, startPositions: Set<Pair<Int, Int>>): Int {
val endPosition = getPosition(input, 'E')
val map = getMap(input)
val visited = mutableSetOf<Pair<Int, Int>>()
val deque = ArrayDeque(listOf(endPosition to 0))
while (deque.isNotEmpty()) {
val current = deque.removeFirst()
if (startPositions.contains(current.first)) {
return current.second
}
availableMoves(current.first, map, endPosition, endPosition)
.filterNot { visited.contains(it) }
.forEach {
deque.addLast(it to current.second + 1)
visited.add(it)
}
}
return -1
}
fun part1(input: List<CharSequence>): Int {
return searchIt(input, setOf(getPosition(input, 'S')))
}
fun part2(input: List<String>): Int {
return searchIt(input, getPositions(input, 'a') + getPosition(input, 'S'))
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("year2022/day$day/test")
val part1Test = part1(testInput)
check(part1Test == expectedTest1) { "expected $expectedTest1 but was $part1Test" }
val input = readInput("year2022/day$day/input")
println(part1(input))
val part2Test = part2(testInput)
check(part2Test == expectedTest2) { "expected $expectedTest2 but was $part2Test" }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 2,890 | adventOfCode | Apache License 2.0 |
src/Day08.kt | Akhunzaada | 573,119,655 | false | {"Kotlin": 23755} | fun main() {
fun List<String>.parseInput(): List<List<Int>> {
val grid = MutableList(size) { MutableList(first().length) { 0 } }
forEachIndexed { i, row ->
row.forEachIndexed { j, c ->
grid[i][j] = c - '0'
}
}
return grid
}
fun isTreeVisible(tree: Int, index: Int, size: Int, next: (index: Int) -> Int): Boolean {
var start = 0; var end = size
while (index in (start + 1) until end) {
val startVal = next(start); val endVal = next(end)
if (startVal >= tree && endVal >= tree)
return false
if (startVal < tree) start++
if (endVal < tree) end--
}
return true
}
fun countVisibleTrees(grid: List<List<Int>>): Int {
var visibleTrees = 0
val n = grid.size-1
val m = grid.first().size-1
for (i in 1 until n) {
for (j in 1 until m) {
val tree = grid[i][j]
if (isTreeVisible(tree, i, n) { c -> grid[c][j] }
|| isTreeVisible(tree, j, m) { r -> grid[i][r] }) {
visibleTrees++
}
}
}
return ((grid.size + grid.first().size - 2) * 2) + visibleTrees
}
fun treeScenicScore(tree: Int, index: Int, size: Int, next: (index: Int) -> Int): Pair<Int, Int> {
var start = index; var end = index
while (start > 0 || end < size) {
var canBreak = false
if (start > 0 && next(start-1) < tree) start--
else canBreak = true
if (end < size && next(end+1) < tree) end++
else if (canBreak) {
if (start != 0) start--
if (end != size) end++
break
}
}
return Pair(start, end)
}
fun highestScenicScore(grid: List<List<Int>>): Int {
var highestScenicScore = 0
val n = grid.size-1
val m = grid.first().size-1
for (i in 0..n) {
for (j in 0..m) {
var distance = 1
val tree = grid[i][j]
val (t, b) = treeScenicScore(tree, i, n) { c -> grid[c][j] }
distance *= i-t
distance *= b-i
val (l, r) = treeScenicScore(tree, j, m) { r -> grid[i][r] }
distance *= j-l
distance *= r-j
highestScenicScore = maxOf(highestScenicScore, distance)
}
}
return highestScenicScore
}
fun part1(input: List<List<Int>>) = countVisibleTrees(input)
fun part2(input: List<List<Int>>) = highestScenicScore(input)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test").parseInput()
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08").parseInput()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b2754454080989d9579ab39782fd1d18552394f0 | 2,998 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day15.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package day15
import aoc.utils.Cursor
import aoc.utils.findInts
import aoc.utils.readInput
import java.math.BigInteger
import kotlin.math.abs
import kotlin.math.max
data class Sensor(val location: Cursor, val beacon: Cursor) {
val distance: Int = location.distance(beacon)
fun covers(point: Cursor) = location.distance(point) <= distance
fun coveredRange(y: Int): ClosedRange<Int>? {
val deltaY = abs(location.y - y)
if (deltaY > distance) {
return null
}
return (location.x - distance + deltaY)..(location.x + distance - deltaY)
}
}
fun part1() {
val rowUnderInspection = 2000000
val sensors = readInput("day15-input.txt")
.map { it.findInts() }
.map { Sensor(Cursor(it[0], it[1]), Cursor(it[2], it[3])) }
val minimumX = sensors.map { it.location.x - it.distance }.minOrNull()!!
val maximumX = sensors.map { it.location.x + it.distance }.maxOrNull()!!
val coveredPositions = (minimumX..maximumX).filter { x ->
val coveredBySensor = sensors.firstOrNull { sensor -> sensor.covers(Cursor(x, rowUnderInspection)) }
coveredBySensor != null
}
val beaconsOnRow = sensors.map { it.beacon }.filter { it.y == rowUnderInspection }.toSet().size
val sensorsOnRow = sensors.map { it.location }.filter { it.y === rowUnderInspection }.toSet().size
val ruledOutPositions = coveredPositions.size - beaconsOnRow - sensorsOnRow
println(ruledOutPositions)
}
fun main() {
val sensors = readInput("day15-input.txt")
.map { it.findInts() }
.map { Sensor(Cursor(it[0], it[1]), Cursor(it[2], it[3])) }
(0..4000000).map { y ->
println(y)
val ranges = sensors.map {
it.coveredRange(y)
}.filterNotNull()
val hasGaps = doesRowContainGaps(ranges)
if (hasGaps) {
(0..4000000).map { x ->
val coveredBySensor = sensors.firstOrNull { sensor -> sensor.covers(Cursor(x, y)) }
if (coveredBySensor == null) {
val result = x.toBigInteger() * (4000000).toBigInteger() + y.toBigInteger()
// 2026291660 too low
println(result)
TODO()
}
}
}
}
}
fun doesRowContainGaps(ranges: List<ClosedRange<Int>>): Boolean {
// For the row to be fully covered there can be no gaps
// this means ranges sorted by start must overlap
val sorted = ranges.sortedBy { it.start }
var combinedEnd = sorted.first().endInclusive
for(range in sorted) {
if(range.start > combinedEnd) {
return true
}
combinedEnd = max(combinedEnd, range.endInclusive)
}
return false
}
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 2,757 | adventOfCode2022 | Apache License 2.0 |
src/Day08.kt | ktrom | 573,216,321 | false | {"Kotlin": 19490, "Rich Text Format": 2301} | fun main() {
fun part1(input: List<String>): Int {
val trees: MutableList<MutableList<Tree>> = mutableListOf()
input.forEachIndexed { y, it ->
trees.add(it.toCharArray().mapIndexed { x, char -> Tree(char.code, x, y) }.toMutableList())
}
return trees.map { row ->
row.map { tree ->
isVisible(tree, trees)
}.sum()
}.sum()
}
fun part2(input: List<String>): Int {
return 1
}
// test if implementation meets criteria from the description
val testInput = readInput("Day08_test")
println(part1(testInput) == 21)
val input = readInput("Day08")
println(part1(input))
println(part2(testInput) == 24933642)
println(part2(input))
}
fun isVisible(tree: Tree, trees: List<List<Tree>>): Int {
Direction.values().forEach { direction ->
if (tree.height > tree.getTallestInDirection(trees, direction)) {
return 1
}
}
return 0
}
class Tree(val height: Int, val xPos: Int, val yPos: Int){
var tallestTree: MutableMap<Direction, Int> = mutableMapOf(
Direction.NORTH to -1,
Direction.EAST to -1,
Direction.SOUTH to -1,
Direction.WEST to -1
)
fun getTallestInDirection(trees: List<List<Tree>>, direction: Direction):Int{
val adjacentTreeY = yPos + yTranslation[direction]!!
val adjacentTreeX = xPos + xTranslation[direction]!!
if (isOutOfBounds(adjacentTreeY, adjacentTreeX, trees)) {
return -1
}
val treeInDirection = trees[adjacentTreeY][adjacentTreeX]
if(treeInDirection.tallestTree[direction] == -1){
treeInDirection.getTallestInDirection(trees, direction)
}
tallestTree[direction] =
treeInDirection.height.coerceAtLeast(treeInDirection.tallestTree[direction]!!)
return tallestTree[direction]!!
}
override fun toString(): String {
return height.toString()
}
}
fun isOutOfBounds(adjacentTreeY: Int, adjacentTreeX: Int, trees: List<List<Tree>>): Boolean{
return adjacentTreeY < 0 || adjacentTreeX < 0 || adjacentTreeY == trees.size || adjacentTreeX == trees[0].size
}
enum class Direction{
NORTH,
EAST,
SOUTH,
WEST
}
val yTranslation: Map<Direction, Int> = mapOf(
Direction.NORTH to -1,
Direction.EAST to 0,
Direction.SOUTH to 1,
Direction.WEST to 0
)
val xTranslation: Map<Direction, Int> = mapOf(
Direction.NORTH to 0,
Direction.EAST to 1,
Direction.SOUTH to 0,
Direction.WEST to -1
)
| 0 | Kotlin | 0 | 0 | 6940ff5a3a04a29cfa927d0bbc093cd5df15cbcd | 2,652 | kotlin-advent-of-code | Apache License 2.0 |
src/Day08.kt | lassebe | 573,423,378 | false | {"Kotlin": 33148} | fun main() {
fun transformInput(input: List<String>) = input.map { line ->
val split = line.split("")
split.subList(1, split.size - 1).map {
it.toInt()
}
}
fun part1(input: List<String>): Int {
val heights = transformInput(input)
return heights.indices.sumOf<Int> { i ->
heights[i].indices.sumOf<Int> { j ->
if (i == 0 || j == 0 || i == heights.size - 1 || j == heights.size - 1) {
return@sumOf 1 as Int // compiler strikes back
}
val currentTree = heights[i][j]
val visibleDirections = listOf(
(0 until i).all { heights[it][j] < currentTree },
(i + 1 until heights.size).all { heights[it][j] < currentTree },
(0 until j).all { heights[i][it] < currentTree },
(j + 1 until heights[i].size).all { heights[i][it] < currentTree })
return@sumOf if (visibleDirections.any { it })
1
else
0
}
}
}
fun visibleTrees(
heights: List<List<Int>>,
currentTree: Int,
fixed: Int,
range: IntProgression,
row: Boolean
): Int {
var count = 0
for (k in range) {
count += 1
if (row) {
if (heights[fixed][k] >= currentTree) {
return count
}
} else {
if (heights[k][fixed] >= currentTree) {
return count
}
}
}
return count
}
fun part2(input: List<String>): Int {
val heights = transformInput(input)
val scenicScores = mutableListOf<Int>()
heights.indices.forEach { i ->
heights[i].indices.forEach { j ->
val currentTree = heights[i][j]
var topCount = visibleTrees(heights, currentTree, j, (i - 1 downTo 0), false)
var bottomCount = visibleTrees(heights, currentTree, j, (i + 1 until heights.size), false)
var leftCount = visibleTrees(heights, currentTree, i, (j - 1 downTo 0), true)
var rightCount = visibleTrees(heights, currentTree, i, (j + 1 until heights[i].size), true)
scenicScores.add(topCount * bottomCount * leftCount * rightCount)
}
}
return scenicScores.maxOf { it }
}
val testInput = readInput("Day08_test")
expect(21, part1(testInput))
val input = readInput("Day08")
expect(1719, part1(input))
println(part1(input))
expect(8, part2(testInput))
println(part2(input))
expect(590824, part2(input))
} | 0 | Kotlin | 0 | 0 | c3157c2d66a098598a6b19fd3a2b18a6bae95f0c | 2,763 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/Day16.kt | gijs-pennings | 573,023,936 | false | {"Kotlin": 20319} | import kotlin.math.max
import kotlin.math.min
private var dist: Array<IntArray> = emptyArray()
fun main() {
val lines = readInput(16)
val n = lines.size
val nameToIndex = lines.withIndex().associate { it.value.substring(6, 8) to it.index }
val nodes = lines.mapIndexed { i, line -> Node(i, line.drop(23).takeWhile(Char::isDigit).toInt()) }
lines.forEachIndexed { i, line ->
nodes[i].adj.addAll(
line.substringAfter("valve").substringAfter(' ').split(", ").map { nodes[nameToIndex[it]!!] }
)
}
dist = Array(n) { IntArray(n) { INF } }
for (i in nodes.indices) dist[i][i] = 0
for (u in nodes)
for (v in u.adj)
dist[u.i][v.i] = 1
for (i in nodes.indices)
for (j in nodes.indices)
for (k in nodes.indices)
dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k])
val first = nodes[nameToIndex["AA"]!!]
println(backtrack(Mob(first), Mob(first), nodes.filter { it.flow > 0 }.toSet()))
}
private fun backtrack(
m1: Mob,
m2: Mob,
nodes: Set<Node>, // list of unvisited next nodes
): Int {
var best = m1.totalFlow + m2.totalFlow
if (m1.time > 0 && m1.time >= m2.time) {
// option 0 : wait at current node
best = max(best, backtrack(Mob(m1.u, 0, m1.fpm, m1.totalFlow + m1.time * m1.fpm), m2, nodes))
// options 1..nodes.size : visit next node
if (m1.time > 1)
for (v in nodes) {
val t = dist[m1.u.i][v.i] + 1
if (t >= m1.time) continue
best = max(best, backtrack(
Mob(v, m1.time - t, m1.fpm + v.flow, m1.totalFlow + t * m1.fpm),
m2,
nodes - v
))
}
}
if (m2.time > 0 && m2.time >= m1.time) {
// option 0 : wait at current node
best = max(best, backtrack(m1, Mob(m2.u, 0, m2.fpm, m2.totalFlow + m2.time * m2.fpm), nodes))
// options 1..nodes.size : visit next node
if (m2.time > 1)
for (v in nodes) {
val t = dist[m2.u.i][v.i] + 1
if (t >= m2.time) continue
best = max(best, backtrack(
m1,
Mob(v, m2.time - t, m2.fpm + v.flow, m2.totalFlow + t * m2.fpm),
nodes - v
))
}
}
return best
}
private data class Node(
val i: Int,
val flow: Int
) {
val adj = mutableListOf<Node>()
}
private data class Mob(
val u: Node, // current node
val time: Int = 26, // leftover time
val fpm: Int = 0, // flow per minute
val totalFlow: Int = 0 // total flow so far
)
| 0 | Kotlin | 0 | 0 | 8ffbcae744b62e36150af7ea9115e351f10e71c1 | 2,731 | aoc-2022 | ISC License |
src/Day07.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | import kotlin.math.min
private data class Node(
val name: String,
val size: Int,
val parent: Node? = null,
val children: MutableList<Node> = mutableListOf(),
) {
val totalSize: Int by lazy { size + children.sumOf { it.totalSize } }
fun isDir(): Boolean = children.isNotEmpty()
}
private fun sumSmallDirectories(node: Node, sizeThres: Int): Int {
if (!node.isDir()) return 0
val currentDir = if (node.totalSize <= sizeThres) node.totalSize else 0
return currentDir + node.children.sumOf { sumSmallDirectories(it, sizeThres) }
}
private fun smallestDirectoryToDelete(node: Node, sizeMin: Int): Int {
if (!node.isDir()) return Int.MAX_VALUE
return min(if (node.totalSize < sizeMin) Int.MAX_VALUE else node.totalSize,
node.children.minOf { smallestDirectoryToDelete(it, sizeMin) })
}
private fun buildDirectoryTree(input: List<String>): Node {
val root = Node("/", 0)
var currentNode = root
input.forEach {
val args = it.split(" ")
when (args[0]) {
"$" -> when (args[1]) {
"cd" -> when (args[2]) {
"/" -> currentNode = root
".." -> currentNode = currentNode.parent!!
else -> currentNode = currentNode.children.find { it.name == args[2] }!!
}
"ls" -> {}
}
"dir" -> {
val name = args[1]
val dir = Node(name, 0, currentNode)
currentNode.children.add(dir)
}
else -> {
val size = args[0].toInt()
val name = args[1]
val file = Node(name, size, currentNode)
currentNode.children.add(file)
}
}
}
return root
}
private const val DISK_SIZE = 70000000
private const val TARGET_FREE_SPACE = 30000000
fun main() {
fun part1(input: List<String>): Int {
val root = buildDirectoryTree(input)
return sumSmallDirectories(root, 100_000)
}
fun part2(input: List<String>): Int {
val root = buildDirectoryTree(input)
val spaceToFree = TARGET_FREE_SPACE - (DISK_SIZE - root.totalSize)
return smallestDirectoryToDelete(root, spaceToFree)
}
val linesTest = readInput("Day07_test")
check(part1(linesTest) == 95437)
check(part2(linesTest) == 24933642)
val lines = readInput("Day07")
println("Part 1")
println(part1(lines))
println("Part 2")
println(part2(lines))
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 2,524 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/y2023/d04/Day04.kt | AndreaHu3299 | 725,905,780 | false | {"Kotlin": 31452} | package y2023.d04
import kotlin.math.pow
import println
import readInput
fun main() {
val classPath = "y2023/d04"
fun score1(input: List<List<Int>>): Int {
val winning = input[0]
val nums = input[1]
return nums
.count { winning.contains(it) }
.let {
if (it == 0) 0 else 2.0.pow((it - 1).toDouble()).toInt()
}
}
fun part1(input: List<String>): Int {
return input.map { card ->
card.split(":")[1].split("|").map { it.trim() }
.let { parts ->
listOf(
parts[0].replace(" ", " ").split(" ").map { it.trim().toInt() },
parts[1].replace(" ", " ").trim().split(" ").map { it.trim().toInt() })
}
}.sumOf { score1(it) }
}
fun score2(input: List<List<Int>>): Int {
val winning = input[0]
val nums = input[1]
return nums.count { winning.contains(it) }
}
fun part2(input: List<String>): Int {
val cards = input.associate { card ->
card.split(":").let { parts ->
Pair(parts[0].trim().substring(4).trim().toInt(),
score2(parts[1].split("|").map { it.trim() }
.let {
listOf(
it[0].replace(" ", " ").split(" ").map { it.trim().toInt() },
it[1].replace(" ", " ").trim().split(" ").map { it.trim().toInt() })
}
))
}
}
val counts = 1.rangeTo(cards.size).associateWith { 1 }.toMutableMap()
for (i in 1..cards.size) {
val cardCount = counts[i]!!
if (cards[i]!! != 0) {
for (j in i + 1..i + cards[i]!!) {
counts[j] = counts[j]!! + cardCount
}
}
}
return counts.values.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${classPath}/test")
part1(testInput).println()
part2(testInput).println()
val input = readInput("${classPath}/input")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e | 2,276 | aoc | Apache License 2.0 |
src/main/kotlin/org/clechasseur/adventofcode2020/math/Math.kt | clechasseur | 318,029,920 | false | null | package org.clechasseur.adventofcode2017.math
import kotlin.math.abs
fun <T> permutations(elements: List<T>): Sequence<List<T>> {
if (elements.size == 1) {
return sequenceOf(listOf(elements.first()))
}
return elements.asSequence().flatMap { elem ->
val subIt = permutations(elements - elem).iterator()
generateSequence { when (subIt.hasNext()) {
true -> listOf(elem) + subIt.next()
false -> null
} }
}
}
fun generatePairSequence(firstRange: IntRange, secondRange: IntRange): Sequence<Pair<Int, Int>> {
return generateSequence(firstRange.first to secondRange.first) { when (it.second) {
secondRange.last -> when (it.first) {
firstRange.last -> null
else -> it.first + 1 to secondRange.first
}
else -> it.first to it.second + 1
} }
}
fun factors(n: Long): List<Long> {
return generateSequence(1L) { when {
it < n -> it + 1L
else -> null
} }.filter { n % it == 0L }.toList()
}
fun greatestCommonDenominator(a: Long, b: Long): Long {
// https://en.wikipedia.org/wiki/Euclidean_algorithm
require(a > 0L && b > 0L) { "Can only find GCD for positive numbers" }
var rm = b
var r = a % rm
while (r != 0L) {
val rm2 = rm
rm = r
r = rm2 % rm
}
return rm
}
fun leastCommonMultiple(a: Long, b: Long): Long {
// https://en.wikipedia.org/wiki/Least_common_multiple
require(a > 0L && b > 0L) { "Can only find LCM for positive numbers" }
return a / greatestCommonDenominator(a, b) * b
}
fun reduceFraction(numerator: Long, denominator: Long): Pair<Long, Long> {
require(denominator != 0L) { "Divide by zero error" }
return when (numerator) {
0L -> 0L to 1L
else -> {
val gcd = greatestCommonDenominator(abs(numerator), abs(denominator))
(numerator / gcd) to (denominator / gcd)
}
}
}
| 0 | Kotlin | 0 | 0 | f3e8840700e4c71e59d34fb22850f152f4e6e739 | 1,951 | adventofcode2020 | MIT License |
src/Day08.kt | vjgarciag96 | 572,719,091 | false | {"Kotlin": 44399} | fun main() {
fun part1(input: List<String>): Int {
return input.flatMapIndexed { j, treeLine ->
treeLine.mapIndexed { i, tree ->
when {
i == 0 || j == 0 || i == treeLine.length - 1 || j == input.size - 1 -> 1
treeLine.substring(0, i).max() < tree -> 1
treeLine.substring(i + 1).max() < tree -> 1
(0 until j).maxOf { input[it][i] } < tree -> 1
(j + 1 until treeLine.length).maxOf { input[it][i] } < tree -> 1
else -> 0
}
}
}.sum()
}
fun part2(input: List<String>): Int {
return input.flatMapIndexed { j, treeLine ->
treeLine.mapIndexed { i, tree ->
var leftScore = treeLine.substring(0, i).takeLastWhile { it < tree }.count()
if (leftScore < i) leftScore++
var rightScore = treeLine.substring(i + 1).takeWhile { it < tree }.count()
if (rightScore < treeLine.length - i - 1) rightScore++
var topScore = (0 until j).reversed().takeWhile { input[it][i] < tree }.count()
if (topScore < (0 until j).count()) topScore++
var bottomScore = (j + 1 until treeLine.length).takeWhile { input[it][i] < tree }.count()
if (bottomScore < (j + 1 until treeLine.length).count()) bottomScore++
leftScore * rightScore * topScore * bottomScore
}
}.max()
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ee53877877b21166b8f7dc63c15cc929c8c20430 | 1,729 | advent-of-code-2022 | Apache License 2.0 |
src/DayEight.kt | jrmacgill | 573,065,109 | false | {"Kotlin": 76362} | import java.lang.Integer.max
fun testTree(i : Int, j : Int, data : Array<IntArray> ) : Int {
val height = data[i][j]
var result = false
for (x in -1..1 ) {
for (y in -1 .. 1) {
if (x == 0 && y == 0) continue
if (x != 0 && y != 0) continue
result = result || testDir(i,j,x,y,height, data)
}
}
return if(result) 1 else 0
}
fun testDir(px : Int, py : Int, dx : Int, dy : Int, height : Int, data: Array<IntArray>) : Boolean {
var x = px+dx
var y = py+dy
while( x in 0 .. data.size-1 && y in 0 .. data.size-1) {
if (data[x][y] >= height) return false
x+=dx
y+=dy
}
return true
}
fun testTreeScore(i : Int, j : Int, data : Array<IntArray> ) : Int {
val height = data[i][j]
var result = 1
for (x in -1..1 ) {
for (y in -1 .. 1) {
if (x == 0 && y == 0) continue
if (x != 0 && y != 0) continue
result = result * testDirScore(i,j,x,y,height, data)
}
}
return result
}
fun testDirScore(px : Int, py : Int, dx : Int, dy : Int, height : Int, data: Array<IntArray>) : Int {
var x = px+dx
var y = py+dy
var distance = 0
while( x in 0 .. data.size-1 && y in 0 .. data.size-1) {
distance++
val tree = data[x][y]
if (tree >= height) return distance
x+=dx
y+=dy
}
return distance
}
fun main() {
val lines = readInput("dayEight")
val size = lines[0].length
val data = Array(size) { IntArray(size) }
lines.forEachIndexed { i, row -> row.forEachIndexed { j, tree -> data[i][j] = tree.digitToInt() } }
var visible = 0
val v = data.mapIndexed{ i, row -> row.mapIndexed{ j, tree -> testTree(i, j, data) }.sum()}.sum()
println(v)
var best = 0
best = data.mapIndexed { i, row -> row.mapIndexed{ j, tree -> testTreeScore(i, j, data) }.max()}.max()
println(best)
}
| 0 | Kotlin | 0 | 1 | 3dcd590f971b6e9c064b444139d6442df034355b | 1,944 | aoc-2022-kotlin | Apache License 2.0 |
kotlin/src/Day15.kt | ekureina | 433,709,362 | false | {"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386} | import java.lang.Integer.parseInt
import java.util.*
fun main() {
fun part1(input: List<String>): Int {
val riskLevels = input.map { line ->
line.map(Char::toString).map(::parseInt)
}
val totalRisks = Array(riskLevels.size) { Array(riskLevels[0].size) { 0 } }
(riskLevels.indices).forEach { row ->
riskLevels[0].indices.forEach { column ->
if (row != 0 || column != 0) {
val backRow = (row - 1).coerceAtLeast(0)
val backColumn = (column - 1).coerceAtLeast(0)
if (row == 0) {
totalRisks[row][column] = totalRisks[row][backColumn] + riskLevels[row][column]
} else if (column == 0) {
totalRisks[row][column] = totalRisks[backRow][column] + riskLevels[row][column]
} else {
totalRisks[row][column] =
minOf(totalRisks[backRow][column], totalRisks[row][backColumn]) + riskLevels[row][column]
}
}
}
}
return totalRisks[riskLevels.size - 1][riskLevels[0].size - 1]
}
fun part2(input: List<String>): Int {
val riskLevelsSmall = input.map { line ->
line.map(Char::toString).map(::parseInt)
}
val riskLevels = Array(riskLevelsSmall.size * 5) { Array(riskLevelsSmall[0].size * 5) { 0 } }
riskLevels.indices.forEach { row ->
riskLevels[0].indices.forEach { column ->
val tileIndex = row / riskLevelsSmall.size to column / riskLevelsSmall[0].size
val cell =
riskLevelsSmall[row % riskLevelsSmall.size][column % riskLevelsSmall[0].size] + tileIndex.first + tileIndex.second
if (cell <= 9) {
riskLevels[row][column] = cell
} else {
riskLevels[row][column] = if (cell % 9 == 0) {
9
} else {
cell % 9
}
}
}
}
val distances = Array(riskLevels.size) { Array(riskLevels[0].size) { Int.MAX_VALUE } }
val queue = PriorityQueue<Pair<Int, Pair<Int, Int>>> { left, right -> left.first.compareTo(right.first) }
queue.addAll(listOf(riskLevels[1][0] to Pair(1, 0), riskLevels[0][1] to Pair(0, 1)))
while (distances[riskLevels.size - 1][riskLevels[0].size - 1] == Int.MAX_VALUE && queue.isNotEmpty()) {
val (distance, nextPoint) = queue.remove()
if (distance < distances[nextPoint.first][nextPoint.second]) {
distances[nextPoint.first][nextPoint.second] = distance
setOf(
Pair(nextPoint.first - 1, nextPoint.second),
Pair(nextPoint.first + 1, nextPoint.second),
Pair(nextPoint.first, nextPoint.second - 1),
Pair(nextPoint.first, nextPoint.second + 1)
).filter { it.first in riskLevels.indices && it.second in riskLevels[0].indices }.forEach { point ->
queue.add((distance + riskLevels[point.first][point.second]) to point)
}
}
}
return distances[riskLevels.size - 1][riskLevels[0].size - 1]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput) == 40) { "${part1(testInput)}" }
check(part2(testInput) == 315) { "${part2(testInput)}" }
val input = readInput("Day15")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 391d0017ba9c2494092d27d22d5fd9f73d0c8ded | 3,703 | aoc-2021 | MIT License |
src/Day13.kt | sebokopter | 570,715,585 | false | {"Kotlin": 38263} | fun main() {
fun parseInput(testInput: String): List<Pair<String, String>> =
testInput
.split("\n\n")
.map {
val (left, right) = it.split("\n")
left to right
}
fun arePacketsInOrder(pair: Pair<String, String>): Boolean {
val (left, right) = pair
println("Compare $left to $right")
if (left.isEmpty()) return true
if (right.isEmpty() && left.isNotEmpty()) return false
val currentLeftElement = left.first()
val currentRightElement = right.first()
if (currentLeftElement.isDigit() && currentRightElement.isDigit()) {
println("Compare2 ${currentLeftElement.digitToInt()} to ${currentRightElement.digitToInt()}")
return when {
currentLeftElement.digitToInt() < currentRightElement.digitToInt() -> true.also { println("result 1: $it") }
currentLeftElement.digitToInt() > currentRightElement.digitToInt() -> false.also { println("result 2: $it") }
else -> arePacketsInOrder(left.drop(2) to right.drop(2)).also { println("result 3: $it") } // drop digit plus ",". E.g. "8,"
}
}
return if (left.startsWith("[[") && right.startsWith("[[")) {
println("Compare3 $currentLeftElement $currentRightElement")
val newLeft = left.drop(1).dropLast(1).split(",")
val newRight = right.drop(1).dropLast(1).split(",")
println("new compare $newLeft $newRight")
arePacketsInOrder(newLeft.joinToString(",") to newRight.joinToString(","))
} else {
when {
currentLeftElement == '[' && currentRightElement == '[' -> {
arePacketsInOrder(
left.drop(1).takeWhile { it != ']'} to right.drop(1).takeWhile { it != ']'}
)
}
currentLeftElement == '[' -> {
arePacketsInOrder(left.drop(1).takeWhile { it != ']'} to right)
}
else -> {
arePacketsInOrder(left to right.drop(1).takeWhile { it != ']'})
}
}
}
}
fun part1(input: List<Pair<String, String>>): Int {
return input.withIndex().sumOf { (index, pair) ->
if (arePacketsInOrder(pair)) index + 1
else 0
}
}
fun part2(input: List<Pair<String, String>>): Int = input.size
val testInput = readTextInput("Day13_test")
val parsedTestInput = parseInput(testInput)
println("part1(testInput): " + part1(parsedTestInput))
// println("part2(parsedInput): " + part2(parsedTestInput))
check(part1(parsedTestInput) == 13)
// check(part2(parsedTestInput) == 24000)
val input = readTextInput("Day13")
val parsedInput = parseInput(input)
println("part1(parsedInput): " + part1(parsedInput))
// println("part2(parsedInput): " + part2(parsedInput))
}
| 0 | Kotlin | 0 | 0 | bb2b689f48063d7a1b6892fc1807587f7050b9db | 2,986 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/_2021/Day9.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2021
import REGEX_LINE_SEPARATOR
import aoc
fun main() {
aoc(2021, 9) {
aocRun { input ->
val grid = parseGrid(input)
val deepestDepths = findDeepestDepths(grid)
return@aocRun deepestDepths.map { (x, y) -> grid[y][x] }.sumOf { it + 1 }
}
aocRun { input ->
val grid = parseGrid(input)
val deepestDepths = findDeepestDepths(grid)
return@aocRun deepestDepths.map { findBasin(grid, it.first, it.second).size }
.sortedDescending()
.take(3)
.reduce { acc, v -> acc * v }
}
}
}
private fun parseGrid(input: String): List<List<Int>> =
input.split(REGEX_LINE_SEPARATOR).map { row -> row.map { it.toString().toInt() } }
private fun findDeepestDepths(grid: List<List<Int>>): List<Pair<Int, Int>> = mutableListOf<Pair<Int, Int>>().apply {
grid.forEachIndexed { y, row ->
row.forEachIndexed { x, depth ->
if (isDeepestDepth(grid, x, y, depth))
this += x to y
}
}
}
private fun getAdjacentPositions(grid: List<List<Int>>, x: Int, y: Int): List<Pair<Int, Int>> {
val gridHeight = grid.size
val gridWidth = grid[0].size
return arrayOf(x to y - 1, x to y + 1, x - 1 to y, x + 1 to y)
.filter { it.first in 0 until gridWidth && it.second in 0 until gridHeight }
}
private fun isDeepestDepth(grid: List<List<Int>>, x: Int, y: Int, depth: Int): Boolean =
getAdjacentPositions(grid, x, y).map { grid[it.second][it.first] }.all { it > depth }
private fun findBasin(grid: List<List<Int>>, x: Int, y: Int): List<Pair<Int, Int>> =
mutableListOf<Pair<Int, Int>>().also { list ->
getAdjacentPositions(grid, x, y).forEach {
findBasinInternal(grid, it.first, it.second, list)
}
}
private fun findBasinInternal(grid: List<List<Int>>, x: Int, y: Int, basin: MutableList<Pair<Int, Int>>) {
val pos = x to y
if (grid[y][x] == 9 || basin.contains(pos))
return
basin += pos
getAdjacentPositions(grid, x, y).filter { !basin.contains(it) }.forEach {
findBasinInternal(grid, it.first, it.second, basin)
}
}
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 1,964 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day4/Day4.kt | alxgarcia | 435,549,527 | false | {"Kotlin": 91398} | package day4
import java.io.File
class BingoBoard(private val numbers: List<List<Int>>) {
private var visited = MutableList(numbers.size) { MutableList(numbers[0].size) { false } }
fun visit(number: Int) {
val traversingCellsIndices = visited.indices.flatMap { r -> visited[0].indices.map { c -> Pair(r, c) } }
val maybeCell = traversingCellsIndices.firstOrNull { (r, c) -> numbers[r][c] == number }
if (maybeCell != null) visited[maybeCell.first][maybeCell.second] = true
}
val isCompleted: Boolean
get() = hasRowCompleted || hasColumnCompleted
private val hasRowCompleted: Boolean
get() = visited.any { row -> row.all { it /* it == true */ } }
private val hasColumnCompleted: Boolean
get() {
val traversingColumnsIndices = visited[0].indices.map { c -> visited.indices.map { r -> Pair(r, c) } }
return traversingColumnsIndices.any { column -> column.all { (r, c) -> visited[r][c] } }
}
fun sumUnvisited(): Int {
val traversingCellsIndices = visited.indices.flatMap { r -> visited[0].indices.map { c -> Pair(r, c) } }
return traversingCellsIndices
.filterNot { (r, c) -> visited[r][c] }
.sumOf { (r, c) -> numbers[r][c] }
}
}
fun findWinnerBoardScore(drawNumbers: List<Int>, boards: List<BingoBoard>): Int {
drawNumbers.forEach { number ->
boards.forEach { board ->
board.visit(number)
if (board.isCompleted) return number * board.sumUnvisited()
}
}
return 0 // should never reach this point
}
fun findLoserBoardScore(drawNumbers: List<Int>, boards: List<BingoBoard>): Int {
val mutBoards = boards.toMutableList()
drawNumbers.forEach { number ->
mutBoards.forEach { board ->
board.visit(number)
if (mutBoards.size == 1 && board.isCompleted) return mutBoards.first().sumUnvisited() * number
}
mutBoards.removeAll { it.isCompleted }
}
return 0 // should never reach this point
}
fun parseBingoData(data: List<String>): Pair<List<Int>, List<BingoBoard>> {
fun parseLine(line: String) = line.split(" ").filterNot(String::isEmpty).map(String::toInt)
fun parseBoard(boardRaw: List<String>) = BingoBoard(boardRaw.map(::parseLine))
val drawNumbers = data.first().split(",").map(String::toInt)
val boards = data
.drop(1) // remove draw numbers
.filterNot(String::isBlank)
.chunked(5)
.map(::parseBoard)
return Pair(drawNumbers, boards)
}
fun main() {
File("./input/day4.txt").useLines { lines ->
val data = lines.toList()
val (drawNumbers, boards) = parseBingoData(data)
println("First value: ${findWinnerBoardScore(drawNumbers, boards)}")
println("Second value: ${findLoserBoardScore(drawNumbers, boards)}")
}
} | 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 2,697 | advent-of-code-2021 | MIT License |
src/Day08.kt | AleksanderBrzozowski | 574,061,559 | false | null | import kotlin.math.max
fun main() {
fun part1() {
val rows = readInput("Day08_test")
val columnsSize = rows[0].length
fun leftTress(rowIndex: Int, columnIndex: Int): List<Int> =
(0 until columnIndex).map { rows[rowIndex][it].digitToInt() }
fun rightTress(rowIndex: Int, columnIndex: Int): List<Int> =
((columnIndex + 1) until columnsSize).map { rows[rowIndex][it].digitToInt() }
fun topTress(rowIndex: Int, columnIndex: Int): List<Int> =
(0 until rowIndex).map { rows[it][columnIndex].digitToInt() }
fun bottomTress(rowIndex: Int, columnIndex: Int): List<Int> =
((rowIndex + 1) until rows.size).map { rows[it][columnIndex].digitToInt() }
var sum = (rows.size * 2) + (columnsSize - 2) * 2
rows.forEachIndexed { i, columns ->
columns.forEachIndexed { j, height ->
if (i == 0 || j == 0 || i == (rows.size - 1) || j == (columns.length - 1)) {
return@forEachIndexed
}
val listOf = listOf(
leftTress(i, j).all { it < height.digitToInt() },
rightTress(i, j).all { it < height.digitToInt() },
topTress(i, j).all { it < height.digitToInt() },
bottomTress(i, j).all { it < height.digitToInt() }
)
val visible = listOf.any { it }
if (visible) {
sum += 1
}
}
}
println(sum)
}
fun part2() {
val rows = readInput("Day08_test")
val columnsSize = rows[0].length
fun leftTrees(rowIndex: Int, columnIndex: Int): List<Int> =
(0 until columnIndex).map { rows[rowIndex][it].digitToInt() }
fun rightTrees(rowIndex: Int, columnIndex: Int): List<Int> =
((columnIndex + 1) until columnsSize).map { rows[rowIndex][it].digitToInt() }
fun topTrees(rowIndex: Int, columnIndex: Int): List<Int> =
(0 until rowIndex).map { rows[it][columnIndex].digitToInt() }
fun bottomTrees(rowIndex: Int, columnIndex: Int): List<Int> =
((rowIndex + 1) until rows.size).map { rows[it][columnIndex].digitToInt() }
fun List<Int>.countVisibleTrees(height: Char): Int = fold(0) { visibleTreesSum, treeHeight ->
when {
height.digitToInt() == treeHeight -> return visibleTreesSum + 1
height.digitToInt() > treeHeight -> visibleTreesSum + 1
else -> return visibleTreesSum + 1
}
}
var highestScenicScore = 0
rows.forEachIndexed { i, columns ->
columns.forEachIndexed { j, height ->
if (i == 0 || j == 0 || i == (rows.size - 1) || j == (columns.length - 1)) {
return@forEachIndexed
}
val leftTrees = leftTrees(i, j).reversed()
val rightTrees = rightTrees(i, j)
val topTrees = topTrees(i, j).reversed()
val bottomTrees = bottomTrees(i, j)
val visibleTreesInEachDirection = listOf(
leftTrees.countVisibleTrees(height),
rightTrees.countVisibleTrees(height),
topTrees.countVisibleTrees(height),
bottomTrees.countVisibleTrees(height)
)
val scenicScore = visibleTreesInEachDirection
.fold(1) { visibleTrees, score ->
visibleTrees * score
}
highestScenicScore = max(highestScenicScore, scenicScore)
}
}
println(highestScenicScore)
}
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 161c36e3bccdcbee6291c8d8bacf860cd9a96bee | 3,776 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/day16/Day16.kt | davidcurrie | 579,636,994 | false | {"Kotlin": 52697} | package day16
import java.io.File
import kotlin.math.max
fun main() {
val regexp = Regex("Valve (.*) has flow rate=(.*); tunnels? leads? to valves? (.*)")
val valves = File("src/day16/input.txt").readLines()
.map { regexp.matchEntire(it)!!.groupValues }.associate { values ->
values[1] to Valve(values[1], values[2].toInt(), values[3].split(", "))
}
val distances = mutableMapOf<Pair<String, String>, Int>()
valves.forEach { (from, valve) -> valves.keys.forEach { to -> distances[Pair(from, to)] = if (from == to) 0 else if (to in valve.leadsTo) 1 else 1000 } }
for (k in valves.keys) {
for (i in valves.keys) {
for (j in valves.keys) {
if (distances[Pair(i, j)]!! > (distances[Pair(i, k)]!! + distances[Pair(k, j)]!!)) {
distances[Pair(i, j)] = distances[Pair(i, k)]!! + distances[Pair(k, j)]!!
}
}
}
}
println(solve(valves, distances, 30))
val nonZeroValves = valves.values.filter { it.rate > 0 }.map { it.name }
var maxRate = 0L
for (i in 0..nonZeroValves.size / 2) {
combinations(nonZeroValves, i).forEach { myValves ->
val myRate = solve(valves.filter { (k, _) -> k == "AA" || k in myValves }, distances, 26)
val elephantRate = solve(valves.filter { (k, _) -> k == "AA" || k !in myValves }, distances, 26)
maxRate = max(maxRate, myRate + elephantRate)
}
}
println(maxRate)
}
fun combinations(values: List<String>, size: Int): Set<Set<String>> {
val result = mutableSetOf<Set<String>>()
combinations(values, ArrayList(), result, size, 0)
return result
}
fun combinations(values: List<String>, current: MutableList<String>, accumulator: MutableSet<Set<String>>, size: Int, pos: Int) {
if (current.size == size) {
accumulator.add(current.toSet())
return
}
for (i in pos..values.size - size + current.size) {
current.add(values[i])
combinations(values, current, accumulator, size, i + 1)
current.removeAt(current.size - 1)
}
}
fun solve(valves: Map<String, Valve>, distances: Map<Pair<String, String>, Int>, maxTime: Int): Long {
val stack = mutableListOf(Path(0, 0, listOf("AA")))
val visited = mutableMapOf<Set<String>, Long>()
var maxRate = 0L
while (stack.isNotEmpty()) {
val path = stack.removeAt(0)
if (path.time > maxTime) continue
if ((visited[path.turnedOn.toSet()] ?: 0) > path.totalRate) continue
visited[path.turnedOn.toSet()] = path.totalRate
val currentName = path.turnedOn.last()
maxRate = max(maxRate, path.totalRate)
valves.values.filter { it.rate != 0 }.filter { it.name !in path.turnedOn }.forEach { valve ->
val distance = distances[Pair(currentName, valve.name)]!!
val turnedOnAt = path.time + distance + 1
stack.add(Path(turnedOnAt, path.totalRate + (valve.rate * (maxTime - turnedOnAt)), path.turnedOn + valve.name))
}
}
return maxRate
}
data class Valve(val name: String, val rate: Int, val leadsTo: List<String>)
data class Path(val time: Int, val totalRate: Long, val turnedOn: List<String>) | 0 | Kotlin | 0 | 0 | 0e0cae3b9a97c6019c219563621b43b0eb0fc9db | 3,243 | advent-of-code-2022 | MIT License |
src/Day03.kt | toninau | 729,811,683 | false | {"Kotlin": 8423} | fun main() {
data class FoundNumber(val id: Int, val number: Int)
data class Point(val x: Int, val y: Int)
fun findPointAdjacentNumbers(
point: Point,
schematic: List<List<Char>>,
numbers: Map<Point, FoundNumber>
): Set<FoundNumber> {
val lineLength = schematic[point.y].size - 1
val startRangeY = if (point.y - 1 > 0) point.y - 1 else 0
val endRangeY = if (point.y + 1 < schematic.size) point.y + 1 else schematic.size - 1
val startRangeX = if (point.x - 1 > 0) point.x - 1 else 0
val endRangeX = if (point.x + 1 < lineLength) point.x + 1 else lineLength - 1
val points = mutableSetOf<FoundNumber>()
for (y in startRangeY..endRangeY) {
for (x in startRangeX..endRangeX) {
if (schematic[y][x].isDigit()) {
numbers[Point(x, y)]?.let { points.add(it) }
}
}
}
return points.toSet()
}
fun findAllNumbers(schematic: List<List<Char>>): Map<Point, FoundNumber> {
val foundNumbers = mutableMapOf<Point, FoundNumber>()
schematic.forEachIndexed { y, line ->
var number = ""
var charStartPositionX = 0
line.forEachIndexed { x, character ->
if (character.isDigit() && number == "") {
charStartPositionX = x
}
if (character.isDigit()) {
number += character
}
if ((x == line.size - 1 && number != "") || (!character.isDigit() && number != "")) {
val foundNumber = FoundNumber("$y$charStartPositionX".toInt(), number.toInt())
foundNumbers[Point(charStartPositionX, y)] = foundNumber
foundNumbers[Point(x - 1, y)] = foundNumber
number = ""
charStartPositionX = 0
}
}
}
return foundNumbers.toMap()
}
fun part1(schematic: List<List<Char>>, allNumbers: Map<Point, FoundNumber>): Int {
val numbersAdjacentToSymbol = mutableSetOf<FoundNumber>()
schematic.forEachIndexed { y, line ->
line.forEachIndexed { x, character ->
if (!character.isDigit() && character != '.') {
numbersAdjacentToSymbol.addAll(findPointAdjacentNumbers(Point(x, y), schematic, allNumbers))
}
}
}
return numbersAdjacentToSymbol.sumOf { it.number }
}
fun part2(schematic: List<List<Char>>, allNumbers: Map<Point, FoundNumber>): Int {
val gearRatios = mutableListOf<Int>()
schematic.forEachIndexed { y, line ->
line.forEachIndexed { x, character ->
if (character == '*') {
val adjacentNumbers = findPointAdjacentNumbers(Point(x, y), schematic, allNumbers)
if (adjacentNumbers.size == 2) {
gearRatios.add(adjacentNumbers.fold(1) { sum, element -> sum * element.number })
}
}
}
}
return gearRatios.sum()
}
val schematic = readInput("Day03").map { it.toList() } // [y][x]
val allNumbers = findAllNumbers(schematic)
println(part1(schematic, allNumbers))
println(part2(schematic, allNumbers))
}
| 0 | Kotlin | 0 | 0 | b3ce2cf2b4184beb2342dd62233b54351646722b | 3,375 | advent-of-code-2023 | Apache License 2.0 |
src/Day04.kt | nielsz | 573,185,386 | false | {"Kotlin": 12807} | fun main() {
fun part1(input: List<String>): Int {
val result = input.map {
val elves = it.split(",")
val elf1 = elves[0].split("-").map { a -> a.toInt() }
val elf2 = elves[1].split("-").map { a -> a.toInt() }
val elf1range = IntRange(elf1[0], elf1[1])
val elf2range = IntRange(elf2[0], elf2[1])
Pair(elf1range, elf2range)
}.map {
if (it.first.overlaps(it.second)) 1 else 0
}.sum()
return result
}
fun part2(input: List<String>): Int {
val result = input.map {
val elves = it.split(",")
val elf1 = elves[0].split("-").map { a -> a.toInt() }
val elf2 = elves[1].split("-").map { a -> a.toInt() }
val elf1range = IntRange(elf1[0], elf1[1])
val elf2range = IntRange(elf2[0], elf2[1])
Pair(elf1range, elf2range)
}.map {
if (it.first.overlapsAnything(it.second)) 1 else 0
}.sum()
return result
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun IntRange.overlaps(other: IntRange): Boolean {
return this.first <= other.first && this.last >= other.last ||
other.first <= this.first && other.last >= this.last
}
private fun IntRange.overlapsAnything(other: IntRange): Boolean {
return this.intersect(other).isNotEmpty()
}
| 0 | Kotlin | 0 | 0 | 05aa7540a950191a8ee32482d1848674a82a0c71 | 1,440 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | Fenfax | 573,898,130 | false | {"Kotlin": 30582} | fun main() {
fun visualTrees(trees: List<Tree>): Int {
var currentHeight = -1
var visibleTrees = 0
for (tree in trees) {
if (tree.treeHeight > currentHeight) {
currentHeight = tree.treeHeight
if (!tree.seen) {
visibleTrees = visibleTrees.inc()
tree.seen = true
}
}
}
return visibleTrees
}
fun calcScore(trees: List<List<Tree>>, startingPoint: Pair<Int, Int>): Int {
var score = 1
var tempScore = 0
val treeSize = trees[startingPoint.first][startingPoint.second].treeHeight
for (x in (startingPoint.first + 1 until trees[startingPoint.first].size).toList()) {
tempScore = tempScore.inc()
if (trees[x][startingPoint.second].treeHeight >= treeSize) {
break
}
}
score *= tempScore
tempScore = 0
for (x in (startingPoint.first - 1 downTo 0).toList()) {
tempScore = tempScore.inc()
if (trees[x][startingPoint.second].treeHeight >= treeSize) {
break
}
}
score *= tempScore
tempScore = 0
for (y in (startingPoint.second + 1 until trees[startingPoint.first].size).toList()) {
tempScore = tempScore.inc()
if (trees[startingPoint.first][y].treeHeight >= treeSize) {
break
}
}
score *= tempScore
tempScore = 0
for (y in (startingPoint.second - 1 downTo 0).toList()) {
tempScore = tempScore.inc()
if (trees[startingPoint.first][y].treeHeight >= treeSize) {
break
}
}
score *= tempScore
return score
}
fun part1(rows: List<List<Tree>>): Int {
val cols = (rows.indices).map { (rows[it].indices).map { i -> rows[i][it] } }
return rows.drop(1).dropLast(1).sumOf { visualTrees(it) } +
rows.drop(1).dropLast(1).sumOf { visualTrees(it.reversed()) } +
cols.drop(1).dropLast(1).sumOf { visualTrees(it) } +
cols.drop(1).dropLast(1).sumOf { visualTrees(it.reversed()) } +
4
}
fun part2(input: List<List<Tree>>): Int {
return (input.indices).maxOf { (input[it].indices).maxOf { y -> calcScore(input, Pair(it, y)) } }
}
val input = readInput("Day08").map { it.toList().map { c -> Tree(c.digitToInt()) } }
println(part1(input))
println(part2(input))
}
data class Tree(val treeHeight: Int, var seen: Boolean = false)
| 0 | Kotlin | 0 | 0 | 28af8fc212c802c35264021ff25005c704c45699 | 2,643 | AdventOfCode2022 | Apache License 2.0 |
src/Day08.kt | JohannesPtaszyk | 573,129,811 | false | {"Kotlin": 20483} | fun main() {
fun String.toRow() = toList().map { it.digitToInt() }
fun List<List<Int>>.getColumn(x: Int) = map { it[x] }
fun part1(input: List<String>): Int {
val heightMap = input.map { it.toRow() }
return heightMap.mapIndexed { y, row ->
row.mapIndexed { x, height ->
val column = heightMap.getColumn(x)
row.subList(0, x).all { it < height }
|| row.subList(x + 1, row.size).all { it < height }
|| column.subList(0, y).all { it < height }
|| column.subList(y + 1, column.size).all { it < height }
}.count { it }
}.sum()
}
fun List<Int>.distanceToHigherOrEvenTree(height: Int): Int {
forEachIndexed { index: Int, tree: Int -> if (tree >= height) return index + 1 }
return size
}
fun part2(input: List<String>): Int {
val heightMap = input.map { it.toRow() }
return heightMap.mapIndexed { y, row ->
row.mapIndexed { x, height ->
val column = heightMap.getColumn(x)
val left = row.subList(0, x).asReversed().distanceToHigherOrEvenTree(height)
val right = row.subList(x + 1, row.size).distanceToHigherOrEvenTree(height)
val top = column.subList(0, y).asReversed().distanceToHigherOrEvenTree(height)
val bottom = column.subList(y + 1, column.size).distanceToHigherOrEvenTree(height)
println("($x,$y) Height:$height L:$left, T:$top, R:$right, B:$bottom")
left * right * top * bottom
}.max()
}.max()
}
val testInput = readInput("Day08_test")
val input = readInput("Day08")
println("Part1 test: ${part1(testInput)}")
check(part1(testInput) == 21)
println("Part 1: ${part1(input)}")
println("Part2 test: ${part2(testInput)}")
check(part2(testInput) == 8)
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 1 | 6f6209cacaf93230bfb55df5d91cf92305e8cd26 | 1,988 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day23.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.*
import kotlin.math.max
import kotlin.math.min
fun main() {
val input = Input.day(23)
println(day23A(input))
println(day23B(input))
}
fun day23A(input: Input): Int {
val map = XYMap(input) { if (it == '#') null else it }
val options = mutableListOf(listOf(Point(1, 0)))
var longest = 0
while (options.isNotEmpty()) {
val next = options.removeFirst()
if (next.last().y == map.height - 1) {
longest = max(longest, next.size - 1)
}
map.adjacents(next.last())
.filter { !next.contains(it.key) }
.filter {
when (it.value) {
'^' -> it.key.y < next.last().y
'v' -> it.key.y > next.last().y
'<' -> it.key.x < next.last().x
'>' -> it.key.x > next.last().x
else -> true
}
}.forEach {
options.add(next + it.key)
}
}
return longest
}
fun day23B(input: Input): Int {
val map = XYMap(input) { if (it == '#') null else it }
val graph = mutableListOf<Graph>()
val meetingPoints = map.all().map { it.key }.filter {
map.adjacents(it).size > 2
}
meetingPoints.forEachIndexed { index, a ->
graph.addAll(
meetingPoints
.drop(index + 1)
.filter { it != a }
.mapNotNull { b ->
getDist(a, b, map)?.let {
Graph(a, b, it)
}
}
)
}
meetingPoints.firstNotNullOf { b ->
getDist(Point(1, 0), b, map)?.let {
Graph(Point(1, 0), b, it)
}
}.let { graph.add(it) }
meetingPoints.firstNotNullOf { b ->
getDist(Point(map.width - 2, map.height - 1), b, map)?.let {
Graph(Point(map.width - 2, map.height - 1), b, it)
}
}.let { graph.add(it) }
val options = mutableListOf(listOf(graph.first { it.a.y == 0 }))
var longest = 0
while (options.isNotEmpty()) {
val next = options.removeFirst()
val on = when {
next.size == 1 -> next.last().b
next.last().a == next[next.size - 2].a -> next.last().b
next.last().a == next[next.size - 2].b -> next.last().b
next.last().b == next[next.size - 2].a -> next.last().a
next.last().b == next[next.size - 2].b -> next.last().a
else -> throw Exception()
}
if (on.y == map.height - 1) {
longest = max(longest, next.sumOf { it.dist })
}
graph
.filter { it.a == on || it.b == on }
.filter { g ->
if(g.a == on) next.none { it.a == g.b || it.b == g.b }
else next.none { it.a == g.a || it.b == g.a }
}
.forEach { options.add(next + it) }
}
return longest
}
private fun getDist(a: Point, b: Point, map: XYMap<Char>): Int? {
val options = mutableListOf(listOf(a))
while (options.isNotEmpty()) {
val next = options.removeFirst()
if(next.last() == b) {
return next.size - 1
}
val nextOptions = map.adjacents(next.last())
.filter { !next.contains(it.key) }
if(nextOptions.size == 1 || next.last() == a) {
nextOptions.forEach {
options.add(next + it.key)
}
}
}
return null
}
class Graph(val a: Point, val b: Point, val dist: Int) | 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 3,526 | AdventOfCode2023 | MIT License |
src/Day18.kt | thpz2210 | 575,577,457 | false | {"Kotlin": 50995} | private class Solution18(input: List<String>) {
val coordinates =
input.map { it.trim().split(",") }.map { Coordinate3D(it[0].toInt(), it[1].toInt(), it[2].toInt()) }.toSet()
val steam = mutableSetOf<Coordinate3D>()
val minX = coordinates.minOf { it.x - 1 }
val maxX = coordinates.maxOf { it.x + 1 }
val minY = coordinates.minOf { it.y - 1 }
val maxY = coordinates.maxOf { it.y + 1 }
val minZ = coordinates.minOf { it.z - 1 }
val maxZ = coordinates.maxOf { it.z + 1 }
fun part1() = coordinates.sumOf { 6 - adjacent(it).count { adjacent -> coordinates.contains(adjacent) } }
fun part2(): Int {
letStreamFlow()
return coordinates.sumOf { adjacent(it).count { adjacent -> steam.contains(adjacent) } }
}
private fun letStreamFlow() {
addBox()
while (true) {
if (!steam.addAll(steam.flatMap { adjacent(it) }.filter { isInBox(it) && !coordinates.contains(it) }))
break
}
}
private fun addBox() {
for (x in minX..maxX)
for (y in minY..maxY) {
steam.add(Coordinate3D(x, y, minZ))
steam.add(Coordinate3D(x, y, maxZ))
}
for (x in minX..maxX)
for (z in minZ..maxZ) {
steam.add(Coordinate3D(x, minY, z))
steam.add(Coordinate3D(x, maxY, z))
}
for (y in minY..maxY)
for (z in minZ..maxZ) {
steam.add(Coordinate3D(minX, y, z))
steam.add(Coordinate3D(maxX, y, z))
}
}
private fun isInBox(coordinate: Coordinate3D) =
coordinate.x in minX..maxX && coordinate.y in minY..maxY && coordinate.z in minZ..maxZ
fun adjacent(coordinate: Coordinate3D) = setOf(
Coordinate3D(coordinate.x + 1, coordinate.y, coordinate.z),
Coordinate3D(coordinate.x - 1, coordinate.y, coordinate.z),
Coordinate3D(coordinate.x, coordinate.y + 1, coordinate.z),
Coordinate3D(coordinate.x, coordinate.y - 1, coordinate.z),
Coordinate3D(coordinate.x, coordinate.y, coordinate.z + 1),
Coordinate3D(coordinate.x, coordinate.y, coordinate.z - 1)
)
data class Coordinate3D(val x: Int, val y: Int, val z: Int)
}
fun main() {
val testSolution = Solution18(readInput("Day18_test"))
check(testSolution.part1() == 64)
check(testSolution.part2() == 58)
val solution = Solution18(readInput("Day18"))
println(solution.part1())
println(solution.part2())
}
| 0 | Kotlin | 0 | 0 | 69ed62889ed90692de2f40b42634b74245398633 | 2,531 | aoc-2022 | Apache License 2.0 |
src/Day18.kt | iam-afk | 572,941,009 | false | {"Kotlin": 33272} | fun main() {
fun List<String>.parse() = this
.map { it.split(',').map { it.toInt() } }
.map { (x, y, z) -> Triple(x, y, z) }
fun part1(cubes: List<Triple<Int, Int, Int>>): Int {
val visited = mutableSetOf<Triple<Int, Int, Int>>()
fun scan(cube: Triple<Int, Int, Int>): Int {
visited += cube
fun go(cube: Triple<Int, Int, Int>): Int = when (cube) {
in visited -> 0
in cubes -> scan(cube)
else -> 1
}
val (x, y, z) = cube
return 0 +
go(Triple(x + 1, y, z)) +
go(Triple(x - 1, y, z)) +
go(Triple(x, y + 1, z)) +
go(Triple(x, y - 1, z)) +
go(Triple(x, y, z + 1)) +
go(Triple(x, y, z - 1))
}
return cubes
.asSequence()
.filter { it !in visited }
.sumOf { scan(it) }
}
fun part2(cubes: List<Triple<Int, Int, Int>>): Int {
var area = part1(cubes)
val minX = cubes.minOf { it.first }
val maxX = cubes.maxOf { it.first }
val minY = cubes.minOf { it.second }
val maxY = cubes.maxOf { it.second }
val minZ = cubes.minOf { it.third }
val maxZ = cubes.maxOf { it.third }
val visited = mutableSetOf<Triple<Int, Int, Int>>()
val outer = mutableSetOf<Triple<Int, Int, Int>>()
fun scanInner(cube: Triple<Int, Int, Int>): Pair<Boolean, Int> {
val (x, y, z) = cube
if (x !in minX..maxX || y !in minY..maxY || z !in minZ..maxZ) return false to 0
visited += cube
fun go(cube: Triple<Int, Int, Int>): Pair<Boolean, Int> = when (cube) {
in cubes -> true to 1
in outer -> false to 0
in visited -> true to 0
else -> scanInner(cube)
}
var result = 0
for ((dx, dy, dz) in arrayOf(
Triple(-1, 0, 0),
Triple(1, 0, 0),
Triple(0, -1, 0),
Triple(0, 1, 0),
Triple(0, 0, -1),
Triple(0, 0, 1)
)) {
val (inner, innerArea) = go(Triple(x + dx, y + dy, z + dz))
if (inner) result += innerArea else return false to 0
}
return true to result
}
for (x in minX..maxX) {
for (y in minY..maxY) {
for (z in minZ..maxZ) {
val cube = Triple(x, y, z)
if (cube !in cubes && cube !in outer && cube !in visited) {
val (inner, innerArea) = scanInner(cube)
if (inner)
area -= innerArea
else {
outer += visited
visited.clear()
}
}
}
}
}
return area
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test").parse()
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18").parse()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b30c48f7941eedd4a820d8e1ee5f83598789667b | 3,353 | aockt | Apache License 2.0 |
src/day08/Day08.kt | skokovic | 573,361,100 | false | {"Kotlin": 12166} | package day08
import readInput
fun createForest(input: List<String>): List<List<Int>> {
return input
.map { it.split("").filter { s -> s.isNotEmpty() }.map(String::toInt).toList() }
.toList()
}
fun isVisible(forest: List<List<Int>>, i: Int, j: Int): Boolean {
val elem = forest[i][j]
return forest.take(i).map { it[j] }.none { it >= elem }
|| forest.takeLast(forest.size - i - 1).map { it[j] }.none { it >= elem }
|| forest[i].take(j).none { it >= elem }
|| forest[i].takeLast(forest.size - j - 1).none { it >= elem }
}
fun countTrees(trees: List<Int>, tree: Int): Int {
if (trees.none { it >= tree }) {
return trees.count()
}
return trees.takeWhile { it < tree }.count() + 1
}
fun calculateScenicScore(forest: List<List<Int>>, i: Int, j: Int): Int {
val tree = forest[i][j]
val up = forest.take(i).map { it[j] }.reversed()
val down = forest.drop(i + 1).map { it[j] }
val left = forest[i].take(j).reversed()
val right = forest[i].drop(j + 1)
return countTrees(up, tree) * countTrees(down, tree) * countTrees(left, tree) * countTrees(right, tree)
}
fun main() {
fun part1(forest: List<List<Int>>): Int {
var count = 0
for (i in forest.indices) {
for (j in forest.indices) {
if (isVisible(forest, i, j)) {
count++
}
}
}
return count
}
fun part2(forest: List<List<Int>>): Int {
var scenicScore = 0
for (i in forest.indices) {
for (j in forest.indices) {
scenicScore = maxOf(scenicScore, calculateScenicScore(forest, i, j))
}
}
return scenicScore
}
val input = readInput("Day08")
val forest = createForest(input)
println(part1(forest))
println(part2(forest))
}
| 0 | Kotlin | 0 | 0 | fa9aee3b5dd09b06bfd5c232272682ede9263970 | 1,895 | advent-of-code-2022 | Apache License 2.0 |
aoc16/day_24/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import pathutils.Pos
import pathutils.fourNeighs
import pathutils.shortest
import java.io.File
fun neighs(pos: Pos, map: List<CharArray>): List<Pos> =
fourNeighs(pos).filter { p -> map[p.x][p.y] != '#' }
fun allDsts(pois: Map<Char, Pos>, map: List<CharArray>): Map<String, Int> {
val dsts = mutableMapOf<String, Int>()
for ((p1, pos1) in pois) {
for ((p2, pos2) in pois) {
if (p1 != p2) {
val d = shortest(pos1, pos2, map, ::neighs)!!.len()
dsts.put("" + p1 + p2, d)
dsts.put("" + p2 + p1, d)
}
}
}
return dsts
}
fun permutations(path: String): List<String> {
if (path.isEmpty())
return listOf(path)
val result = mutableListOf<String>()
for ((i, p) in path.withIndex()) {
for (perm in permutations(path.removeRange(i, i + 1)))
result.add(p + perm)
}
return result
}
fun shortestPath(start: Char, end: String, through: String, dsts: Map<String, Int>): Int =
permutations(through).map { perm ->
(perm + end).fold(start to 0) { (curr, dst), next ->
next to dst + dsts["" + curr + next]!!
}.second
}.minOrNull()!!
fun main() {
val map = File("input").readLines().map { it.toCharArray() }
val pois = map
.withIndex()
.flatMap { (x, row) ->
row
.withIndex()
.filter { (_, c) -> c.isDigit() }
.map { (y, poi) -> poi to Pos(x, y) }
}.toMap()
.toMutableMap()
val dsts = allDsts(pois, map)
pois.remove('0')
val first = shortestPath('0', "", pois.keys.joinToString(""), dsts)
println("First: $first")
val second = shortestPath('0', "0", pois.keys.joinToString(""), dsts)
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,815 | advent-of-code | MIT License |
src/day08/Day08.kt | gillyobeast | 574,413,213 | false | {"Kotlin": 27372} | package day08
import utils.*
import kotlin.math.max
fun part1(input: List<String>): Int {
return countVisible(matrixOf(input))
}
private fun countVisible(matrix: Matrix<Int>): Int {
var visible = 0
matrix.iterate { rowIndex, colIndex ->
val (row, column, tree) = matrix[rowIndex, colIndex]
val (treesBefore, treesAfter) = row.beforeAndAfter(colIndex)
val (treesAbove, treesBelow) = column.beforeAndAfter(rowIndex)
if (!treesBefore.blocks(tree) || !treesAfter.blocks(tree) || !treesAbove.blocks(tree) || !treesBelow.blocks(
tree
)
) visible++
}
return visible
}
private fun <E> Matrix<E>.iterate(block: (Int, Int) -> Unit) {
indices.forEach { rowIndex ->
this[rowIndex].indices.forEach { colIndex ->
block(
rowIndex, colIndex
)
}
}
}
private fun List<Int>.blocks(tree: Int) = any { it >= tree }
private fun matrixOf(input: List<String>) = input.map {
it.split("").filter(String::isNotBlank).map(String::toInt).toList()
}
fun part2(input: List<String>): Int {
val matrix = matrixOf(input)
var maxScenicScore = 0
var maxTree = -1 to -1
// from each tree, calculate view distance in each direction
// multiply to get scenicScore
// take max of max,
matrix.iterate { rowIndex, colIndex ->
val (row, column, tree) = matrix[rowIndex, colIndex]
val hori = tree.viewDistanceInDirection(row, colIndex)
val vert = tree.viewDistanceInDirection(column, rowIndex)
val scenicScore = hori * vert
if (scenicScore > maxScenicScore)
maxTree = colIndex + 1 to rowIndex + 1
maxScenicScore = max(scenicScore, maxScenicScore)
}
println("maxTree = $maxTree")
return maxScenicScore
}
private fun Int.viewDistanceInDirection(
column: List<Int>,
rowIndex: Int
): Int {
val direction = column.beforeAndAfter(rowIndex)
val viewDistanceBefore = viewDistanceTo(direction.first.asReversed())
val viewDistanceAfter = viewDistanceTo(direction.second)
return viewDistanceBefore * viewDistanceAfter
}
fun Int.viewDistanceTo(trees: List<Int>): Int {
return if (trees.any { it >= this })
trees.indexOfFirst { it >= this } + 1
else
trees.size
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("input_test")
val input = readInput("input")
// part 1
// ::part1.appliedTo(testInput, returns = 21)
// println("Part 1: ${part1(input).shouldNotBe(equalTo = 1071)}")
// part 2
::part2.appliedTo(testInput, returns = 8)
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 8cdbb20c1a544039b0e91101ec3ebd529c2b9062 | 2,730 | aoc-2022-kotlin | Apache License 2.0 |
src/year2022/day12/Day12.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day12
import check
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day12_test")
check(part1(testInput), 31)
check(part2(testInput), 29)
val input = readInput("2022", "Day12")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val (graph, start, target) = parseInput(input) { it <= 1 }
val shortestPath = findShortestPath(graph, start) { it == target }
return shortestPath.size - 1
}
private fun part2(input: List<String>): Int {
val (graph, _, target) = parseInput(input) { it >= -1 }
val shortestPath = findShortestPath(graph, target) { it.height == 0 }
return shortestPath.size - 1
}
private fun findShortestPath(graph: Map<Pos, List<Pos>>, start: Pos, isTarget: (Pos) -> Boolean): List<Pos> {
val stack = ArrayDeque<List<Pos>>()
val visited = mutableSetOf(start)
stack.addLast(listOf(start))
while (stack.isNotEmpty()) {
val path = stack.removeFirst()
val current = path.last()
val ways = graph[current] ?: emptyList()
for (next in ways) {
if (next !in visited) {
visited += next
val newPath = path + next
if (isTarget(next)) return newPath
stack.addLast(newPath)
}
}
}
error("no path found")
}
private fun parseInput(input: List<String>, isWay: (Int) -> Boolean): PuzzleInput {
val maxX = input.first().lastIndex
val maxY = input.lastIndex
val graph = mutableMapOf<Pos, List<Pos>>()
lateinit var start: Pos
lateinit var target: Pos
input.forEachIndexed { y, line ->
line.forEachIndexed { x, char ->
val pos = Pos(x, y, char.height)
val ways = mutableListOf<Pos>()
if (char == 'S') start = pos
if (char == 'E') target = pos
if (x > 0 && isWay(input[y][x - 1].height - char.height)) ways += Pos(x - 1, y, input[y][x - 1].height)
if (x < maxX && isWay(input[y][x + 1].height - char.height)) ways += Pos(x + 1, y, input[y][x + 1].height)
if (y > 0 && isWay(input[y - 1][x].height - char.height)) ways += Pos(x, y - 1, input[y - 1][x].height)
if (y < maxY && isWay(input[y + 1][x].height - char.height)) ways += Pos(x, y + 1, input[y + 1][x].height)
graph[pos] = ways
}
}
return PuzzleInput(
graph = graph,
start = start,
target = target,
)
}
private val Char.height: Int
get() = when (this) {
'S' -> 'a'
'E' -> 'z'
else -> this
} - 'a'
private data class Pos(val x: Int, val y: Int, val height: Int)
private data class PuzzleInput(
val graph: Map<Pos, List<Pos>>,
val start: Pos,
val target: Pos,
) | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 2,887 | AdventOfCode | Apache License 2.0 |
2023/src/main/kotlin/Day25.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day25 {
fun part1(input: String): Int {
val graph = parse(input)
// Find the components with the shortest paths to every other node - those *must* be the nodes between the two groups
val distances = graph.keys
.map { component -> Distance(component, furthestComponent(component, graph)) }
.sortedBy { it.distance }
val shortestDistanceComponents = distances
.filter { it.distance == distances[0].distance }
.map { it.component }
// Try removing each edge from the nodes; the result that has the highest distance (because it has to cross the gap
// at a different point) is the one that needs to be cut, then cut it from the graph
val dividedGraph = graph.toMutableMap()
shortestDistanceComponents.forEach { component ->
// Try removing each edge from the start from the graph. The result w/ the highest distance
// must be the one connecting the groups (since cutting it means you have to "the long way" now).
val componentToCut = graph[component]!!
.map { ignoredComponent -> Distance(ignoredComponent, furthestComponent(component, graph, ignoredComponent)) }
.maxBy { it.distance }
.component
// Cut the longest path from the graph
dividedGraph[component] = dividedGraph[component]!! - componentToCut
dividedGraph[componentToCut] = dividedGraph[componentToCut]!! - component
}
// Find the size of one group and you have the size of the other
val group1 = numberOfReachableComponents(graph.keys.first(), dividedGraph)
val group2 = graph.keys.size - group1
return group1 * group2
}
private fun furthestComponent(start: String, graph: Map<String, List<String>>, ignoreEdge: String? = null): Int {
val queue = java.util.ArrayDeque<Distance>()
val visited = mutableMapOf(start to 0)
queue.addAll(graph[start]!!
.filter { it != ignoreEdge }
.map { Distance(it, 1) }
)
while (queue.isNotEmpty()) {
val (component, distance) = queue.pop()
if (visited.containsKey(component)) {
continue
}
visited[component] = distance
queue.addAll(graph[component]!!.map { Distance(it, distance + 1) })
}
return visited.maxOf { it.value }
}
private fun numberOfReachableComponents(start: String, graph: Map<String, List<String>>): Int {
val queue = java.util.ArrayDeque<String>()
val visited = mutableSetOf(start)
queue.addAll(graph[start]!!)
while (queue.isNotEmpty()) {
val component = queue.pop()
if (component in visited) {
continue
}
visited.add(component)
queue.addAll(graph[component]!!)
}
return visited.size
}
private data class Distance(val component: String, val distance: Int)
private fun parse(input: String): Map<String, List<String>> {
val map = mutableMapOf<String, MutableList<String>>()
fun connect(a: String, b: String) {
map.getOrPut(a) { mutableListOf() }.add(b)
map.getOrPut(b) { mutableListOf() }.add(a)
}
input.splitNewlines().forEach { line ->
val components = line.splitWhitespace()
val a = components[0].dropLast(1)
components.drop(1).forEach { b -> connect(a, b) }
}
return map
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 3,259 | advent-of-code | MIT License |
src/year2022/day09/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2022.day09
import java.util.function.Predicate
import kotlin.math.abs
import readInput
fun main() {
val day = "09"
val expectedTest1 = 13
val expectedTest2 = 1
data class Point(val x: Int, val y: Int) {
fun isNear(point: Point): Boolean = abs(x - point.x) <= 1 && abs(y - point.y) <= 1
fun move(dir: Char, conditional: Predicate<Point> = Predicate<Point> { false }): Point {
return when {
conditional.test(this) -> this
else -> when (dir) {
'R' -> Point(x + 1, y)
'L' -> Point(x - 1, y)
'U' -> Point(x, y + 1)
'D' -> Point(x, y - 1)
else -> throw IllegalArgumentException("invalid dir")
}
}
}
fun nearer(a: Int, b: Int) =
when {
a < b -> a + 1
a == b -> a
else -> a - 1
}
fun moveNear(conditional: Point) = when {
this.isNear(conditional) -> this
else -> Point(nearer(x, conditional.x), nearer(y, conditional.y))
}
}
data class MapIndex(
val head: List<Point>,
val tail: Point,
val visited: Set<Point>,
)
fun asMoveSequence(input: List<String>) = input.map { it.split(" ") }.flatMap { l -> l[0].repeat(l[1].toInt()).asSequence() }
fun part1(input: List<String>): Int {
val map = asMoveSequence(input).fold(MapIndex(listOf(Point(0, 0)), Point(0, 0), setOf())) { acc, mov ->
val newHead = listOf(acc.head.last().move(mov))
val newTail = acc.tail.moveNear(newHead.last())
MapIndex(newHead, newTail, acc.visited + newTail)
}
return map.visited.size
}
// 0 0 0 0 0 0 0 0 0 1 2
fun part2(input: List<String>): Int {
val map = asMoveSequence(input).fold(MapIndex(List(10){Point(0, 0)}, Point(0, 0), setOf())) { acc, mov ->
val newHead = acc.head.take(9).foldRight(listOf(acc.head.last().move(mov))){
i, positions -> listOf( i.moveNear(positions.first())) + positions
}.takeLast(10)
val newTail = newHead.first()
MapIndex(newHead, newTail, acc.visited + newTail)
}
return map.visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("year2022/day$day/test")
val part1Test = part1(testInput)
check(part1Test == expectedTest1)
{ "expected $expectedTest1 but was $part1Test" }
val input = readInput("year2022/day$day/input")
println(part1(input))
val part2Test = part2(testInput)
check(part2Test == expectedTest2)
{ "expected $expectedTest2 but was $part2Test" }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 2,851 | adventOfCode | Apache License 2.0 |
src/Day12.kt | zirman | 572,627,598 | false | {"Kotlin": 89030} | data class Sqr(val rowIndex: Int, val colIndex: Int)
fun main() {
fun parseMap(input: List<String>): List<List<Int>> {
return input.map { line ->
line.map { c ->
if (c == 'S') 0 else c - 'a'
}
}
}
fun search(
map: List<List<Int>>,
nextSqrs: Set<Sqr>,
nextPredicate: (Int, Int) -> Boolean,
endPredicate: (Sqr, Int) -> Boolean,
): Int {
val rowIndices = map.indices
val colIndices = map.first().indices
tailrec fun search(searchDepth: Int, nextSqrs: Set<Sqr>, visitedSqrs: Set<Sqr>): Int {
return when {
nextSqrs.any { endPredicate(it, map[it.rowIndex][it.colIndex]) } -> searchDepth + 1
else -> {
search(
searchDepth + 1,
nextSqrs
.flatMap { (ri, ci) ->
val height = map[ri][ci]
buildList {
if (rowIndices.contains(ri - 1) && nextPredicate(height, map[ri - 1][ci])) {
val sqr = Sqr(ri - 1, ci)
if (visitedSqrs.contains(sqr).not()) add(sqr)
}
if (rowIndices.contains(ri + 1) && nextPredicate(height, map[ri + 1][ci])) {
val sqr = Sqr(ri + 1, ci)
if (visitedSqrs.contains(sqr).not()) add(sqr)
}
if (colIndices.contains(ci - 1) && nextPredicate(height, map[ri][ci - 1])) {
val sqr = Sqr(ri, ci - 1)
if (visitedSqrs.contains(sqr).not()) add(sqr)
}
if (colIndices.contains(ci + 1) && nextPredicate(height, map[ri][ci + 1])) {
val sqr = Sqr(ri, ci + 1)
if (visitedSqrs.contains(sqr).not()) add(sqr)
}
}
}
.toSet(),
visitedSqrs.union(nextSqrs)
)
}
}
}
return search(0, nextSqrs, emptySet())
}
fun findEnd(map: List<List<Int>>): Sqr {
val rowIndices = map.indices
val colIndices = map.first().indices
return rowIndices
.flatMap { rowIndex ->
colIndices.map { colIndex ->
Triple(rowIndex, colIndex, map[rowIndex][colIndex])
}
}
.maxBy { (_, _, h) -> h }
.let { (r, c) -> Sqr(r, c) }
}
fun part1(input: List<String>): Int {
val map = parseMap(input)
val start = input.asSequence()
.flatMapIndexed { rowIndex, row ->
row.mapIndexed { colIndex, s ->
Pair(s, Sqr(rowIndex, colIndex))
}
}
.first { (s) -> s == 'S' }
.second
val end = findEnd(map)
return search(
map = map,
nextSqrs = setOf(start),
nextPredicate = { height, nextHeight -> height + 1 >= nextHeight },
endPredicate = { sqr, _ -> sqr == end },
)
}
fun part2(input: List<String>): Int {
val map = parseMap(input)
val end = findEnd(map)
return search(
map = map,
nextSqrs = setOf(end),
endPredicate = { _, height -> height == 0 },
nextPredicate = { height, nextHeight -> nextHeight >= height - 1 },
)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
val input = readInput("Day12")
println(part1(input))
check(part2(testInput) == 29)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 2ec1c664f6d6c6e3da2641ff5769faa368fafa0f | 4,172 | aoc2022 | Apache License 2.0 |
src/year_2023/day_04/Day04.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2023.day_04
import readInput
data class ScratchCard(
val cardNumber: Int,
val winningNumbers: List<Int>,
val myNumbers: List<Int>
) {
val matchingNumbers: Set<Int> get() {
return winningNumbers.intersect(myNumbers.toSet())
}
val score: Int get() {
var points = 0
matchingNumbers.forEach { _ ->
points = if (points == 0) 1 else points * 2
}
return points
}
}
object Day04 {
/**
*
*/
fun solutionOne(text: List<String>): Int {
return parseCards(text).sumOf { it.score }
}
/**
*
*/
fun solutionTwo(text: List<String>): Int {
val originalCards = parseCards(text)
val cardCounts = mutableMapOf<Int, Int>() // card number to count
originalCards.forEach { card ->
cardCounts[card.cardNumber] = 1
}
originalCards.forEachIndexed { index, scratchCard ->
val cardCount = cardCounts[scratchCard.cardNumber] ?: 1
for (winIndex in scratchCard.cardNumber + 1..scratchCard.cardNumber + scratchCard.matchingNumbers.size ) {
cardCounts[winIndex] = ((cardCounts[winIndex] ?: 0) + cardCount)
}
}
return cardCounts.toList().sumOf { it.second }
}
private fun parseCards(text: List<String>): List<ScratchCard> {
return text.map { line ->
val split = line.split(":")
val cardNumber = split[0].split(" ").filter { it.isNotEmpty() }[1].replace(":", "").toInt()
val numbers = split[1].split("|")
val winningNumbers = numbers[0].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
val myNumbers = numbers[1].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
ScratchCard(cardNumber, winningNumbers, myNumbers)
}
}
}
fun main() {
val text = readInput("year_2023/day_04/Day04.txt")
Thread.sleep(1000)
val solutionOne = Day04.solutionOne(text)
println("Solution 1: $solutionOne")
val solutionTwo = Day04.solutionTwo(text)
println("Solution 2: $solutionTwo")
}
| 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 2,139 | advent_of_code | Apache License 2.0 |
src/Day03.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | fun main() {
fun prio(a: Char): Int {
if (a in 'a'..'z') return a - 'a' + 1
if (a in 'A'..'Z') return a - 'A' + 27
return 0
}
fun part1(input: List<String>): Int {
return input.filter { return@filter it.isNotEmpty() }.sumOf {
val firstHalf = it.slice(0 until it.length / 2)
.map { c -> return@map prio(c) }
.sorted()
val secondHalf = it.slice((it.length / 2) until it.length)
.map { c -> return@map prio(c) }
.sorted()
var i = 0
var j = 0
while (i < firstHalf.size && j < secondHalf.size) {
if (firstHalf[i] < secondHalf[j]) {
i++
} else if (firstHalf[i] > secondHalf[j]) {
j++
} else {
return@sumOf firstHalf[i]
}
}
return@sumOf 0
}
}
fun part2(input: List<String>): Int {
return input.filter { return@filter it.isNotEmpty() }.chunked(3).sumOf {
val a = it[0].map { c -> return@map prio(c) }.sorted()
val b = it[1].map { c -> return@map prio(c) }.sorted()
val c = it[2].map { c -> return@map prio(c) }.sorted()
var i = 0
var j = 0
var k = 0
while (i < a.size && j < b.size && k < c.size) {
if (a[i] == b[j] && b[j] == c[k]) {
return@sumOf a[i]
} else if (a[i] <= b[j] && a[i] <= c[k]) {
i++
} else if (b[j] <= a[i] && b[j] <= c[k]) {
j++
} else {
k++
}
}
return@sumOf 0
}
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 2,002 | aoc-2022 | Apache License 2.0 |
src/Day08.kt | dcbertelsen | 573,210,061 | false | {"Kotlin": 29052} | import java.io.File
fun main() {
fun sightAlongAndMark(trees: List<Tree>) {
var max = -1
trees.forEach { t -> if (t.height > max) { t.canSee(); max = t.height }}
}
fun getVisibleTrees(trees: List<Tree>): Int {
var count = 0
var max = 0
for (tree in trees.subList(1, trees.size)) {
count++
max = maxOf(max, tree.height)
if (tree.height >= trees[0].height) {
break
}
}
return count
}
fun <T> getColumns(ts: List<List<T>>): List<List<T>> {
return (0 until ts[0].size).map { i ->
ts.map { r -> r[i] }.toList()
}.toList()
}
fun getDirectionLists(trees: List<List<Tree>>, row: Int, col: Int): List<List<Tree>> {
val directions = mutableListOf<List<Tree>>()
directions.add(trees[row].subList(0, col+1).reversed()) // left
directions.add(trees[row].subList(col, trees[row].size)) // right
val column = getColumns(trees)[col]
directions.add(column.subList(0, row+1).reversed()) // top
directions.add(column.subList(row, column.size)) // bottom
return directions.toList()
}
fun part1(input: List<String>): Int {
val forest = input.map { r -> r.map { Tree(it.digitToInt()) }}
forest.forEach { sightAlongAndMark(it) }
forest.forEach { sightAlongAndMark(it.reversed()) }
val columns = getColumns(forest)
columns.forEach { sightAlongAndMark(it) }
columns.forEach { sightAlongAndMark(it.reversed()) }
// forest.forEach { r -> println(r.joinToString("") { t -> "${t}" }) }
println()
return forest.flatten().count { it.isVisible }
}
fun part2(input: List<String>): Int {
val forest = input.map { r -> r.map { Tree(it.digitToInt()) }}
forest.forEachIndexed { i, row -> row.forEachIndexed { j, tree ->
val lists = getDirectionLists(forest, i, j)
tree.scenicScore = lists.map {
getVisibleTrees(it)
}.fold(1) { acc, it -> it * acc }
} }
// forest.forEach { r -> println(r.joinToString(" ") { t -> "${t.scenicScore}" }) }
println()
return forest.flatten().maxOf { it.scenicScore }
}
val testInput = listOf<String>(
"30373",
"25512",
"65332",
"33549",
"35390"
)
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = File("./src/resources/Day08.txt").readLines()
println(part1(input))
println(part2(input))
}
class Tree(val height: Int, var isVisible: Boolean = false) {
fun canSee() { isVisible = true }
override fun toString(): String = if (isVisible) "*" else " "
var scenicScore = -1
}
| 0 | Kotlin | 0 | 0 | 9d22341bd031ffbfb82e7349c5684bc461b3c5f7 | 2,880 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/poyea/aoc/mmxxii/day07/Day07.kt | poyea | 572,895,010 | false | {"Kotlin": 68491} | package poyea.aoc.mmxxii.day07
import poyea.aoc.utils.readInput
import kotlin.Int.Companion.MAX_VALUE
import kotlin.math.min
class Node(val path: String, var size: Int, val isDir: Boolean, val parent: Node?, val children: MutableSet<Node>)
fun buildSize(node: Node?): Int {
if (node == null) {
return 0
}
var sum = 0
if (!node.isDir) {
return node.size
}
for (child in node.children) {
sum += buildSize(child)
}
node.size = sum
// println("${node.path} : ${node.size}")
return sum
}
fun filterSize(node: Node?, limit: Int): Int {
if (node == null) {
return 0
}
var sum = 0
if (node.isDir) {
sum += if (node.size <= limit) node.size else 0
}
for (child in node.children) {
sum += filterSize(child, limit)
}
return sum
}
fun filterNode(node: Node?, toRelease: Int, hasSpaceOf: Int): Int {
if (node == null || !node.isDir) {
return MAX_VALUE
}
var newRelease = if (node.size in hasSpaceOf..toRelease) node.size else toRelease
for (child in node.children) {
if (child.isDir) {
newRelease = min(newRelease, filterNode(child, newRelease, hasSpaceOf))
}
}
return newRelease
}
fun buildTree(input: String): Node {
var tree = Node("/", 0, true, null, mutableSetOf())
val root = tree
input.split("\n").forEach {
if (it.startsWith("$")) {
val commandList = it.split(" ")
val command = commandList[1]
val parentPath = if (tree.path == "/") "" else tree.path
when (command) {
"ls" -> {}
"cd" -> {
val destination = commandList[2]
if (destination == "..") {
tree = tree.parent!!
} else {
if (destination != "/") {
tree = tree.children.find { it.path == "$parentPath/$destination" }!!
}
}
}
else -> {}
}
} else {
val commandList = it.split(" ")
val sizeOrDir = commandList[0]
val name = commandList[1]
val parentPath = if (tree.path == "/") "" else tree.path
val parentSize = tree.size
when (sizeOrDir) {
"dir" -> {
tree.children.add(Node("$parentPath/$name", parentSize, true, tree, mutableSetOf()))
}
else -> {
val size = sizeOrDir.toInt()
if (tree.children.firstOrNull { it.path == "$parentPath/$name" } == null) {
tree.children.add(Node("$parentPath/$name", parentSize + size, false, tree, mutableSetOf()))
} else {
tree.children.first { it.path == "$parentPath/$name" }.size += size
}
}
}
}
}
return root
}
fun part1(input: String): Int {
buildTree(input).let {
buildSize(it)
return filterSize(it, 100000)
}
}
fun part2(input: String): Int {
buildTree(input).let {
buildSize(it)
return if (it.size >= 30000000) {
filterNode(it, MAX_VALUE, 30000000 - (70000000 - it.size))
} else {
0
}
}
}
fun main() {
println(part1(readInput("Day07")))
println(part2(readInput("Day07")))
}
| 0 | Kotlin | 0 | 1 | fd3c96e99e3e786d358d807368c2a4a6085edb2e | 3,495 | aoc-mmxxii | MIT License |
app/src/main/kotlin/day09/Day09.kt | W3D3 | 433,748,408 | false | {"Kotlin": 72893} | package day09
import common.InputRepo
import common.colored
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 9
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay09Part1, ::solveDay09Part2)
}
private fun parseInput(input: List<String>): List<List<Int>> {
return input.map { line -> line.map { c -> c.digitToInt() } }
}
data class Point(val x: Int, val y: Int, val height: Int)
private fun getLowPoints(map: List<List<Int>>, print: Boolean = false): ArrayList<Point> {
val lowPoints = ArrayList<Point>()
for (i in map.indices) {
for (j in map[i].indices) {
val currentPoint = map[i][j]
val neighbors = setOf(
pointAt(map, i + 1, j),
pointAt(map, i, j + 1),
pointAt(map, i - 1, j),
pointAt(map, i, j - 1),
).filterNotNull()
if (neighbors.all { it.height > currentPoint }) {
lowPoints += Point(i, j, currentPoint)
if (print) colored { print(currentPoint.toString().red) }
} else {
if (print) print(currentPoint)
}
}
if (print) println()
}
return lowPoints
}
fun solveDay09Part1(input: List<String>): Int {
val heightMap = parseInput(input)
return getLowPoints(heightMap).sumOf { p -> p.height + 1 }
}
private fun findBasin(map: List<List<Int>>, point: Point, visited: Set<Point> = mutableSetOf(point)): Set<Point> {
val i = point.x
val j = point.y
var newVisited: Set<Point>
val unvisitedNeighbors = setOf(
pointAt(map, i + 1, j),
pointAt(map, i, j + 1),
pointAt(map, i - 1, j),
pointAt(map, i, j - 1),
)
.filterNotNull()
.filter { value -> value.height < 9 }
.filter { value -> !visited.contains(value) }
if (unvisitedNeighbors.isEmpty())
return emptySet()
newVisited = visited union unvisitedNeighbors union setOf(point)
for (neighbor in unvisitedNeighbors) {
newVisited = newVisited + findBasin(map, neighbor, newVisited)
}
return newVisited
}
private fun pointAt(map: List<List<Int>>, x: Int, y: Int): Point? {
val value = map.getOrNull(x)?.getOrNull(y) ?: return null
return Point(x, y, value)
}
fun solveDay09Part2(input: List<String>): Int {
val heightMap = parseInput(input)
val lowPoints = getLowPoints(heightMap)
return lowPoints.map { findBasin(heightMap, it).size }
.sortedDescending()
.take(3)
.reduce { x, y -> x * y }
}
| 0 | Kotlin | 0 | 0 | df4f21cd99838150e703bcd0ffa4f8b5532c7b8c | 2,638 | AdventOfCode2021 | Apache License 2.0 |
src/Day04.kt | papichulo | 572,669,466 | false | {"Kotlin": 16864} | fun main() {
fun overlapsComplete(s1List: List<Int>, s2List: List<Int>): Int {
return if ((s1List.first() <= s2List.first() && s1List.last() >= s2List.last()) ||
(s2List.first() <= s1List.first() && s2List.last() >= s1List.last())) 1 else 0
}
fun overlapsPartially(s1List: List<Int>, s2List: List<Int>): Int {
return if ((s1List.first() <= s2List.first() && s1List.last() >= s2List.first()) ||
(s1List.first() <= s2List.last() && s1List.last() >= s2List.last()) ||
(s2List.first() <= s1List.first() && s2List.last() >= s1List.first()) ||
(s2List.first() <= s1List.last() && s2List.last() >= s1List.last())) 1 else 0
}
fun overlaps(s1: String, s2: String, complete: Boolean = true): Int {
val s1List = s1.split('-').map { it.toInt() }
val s2List = s2.split('-').map { it.toInt() }
return if (complete) overlapsComplete(s1List, s2List) else overlapsPartially(s1List, s2List)
}
fun part2(input: List<String>): Int {
return input.map { t -> t.split(',') }
.sumOf { overlaps(it.first(), it.last(), false) }
}
fun part1(input: List<String>): Int {
return input.map { t -> t.split(',') }
.sumOf { overlaps(it.first(), it.last()) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e277ee5bca823ce3693e88df0700c021e9081948 | 1,589 | aoc-2022-in-kotlin | Apache License 2.0 |
src/year2022/day08/Solution.kt | LewsTherinTelescope | 573,240,975 | false | {"Kotlin": 33565} | package year2022.day08
import utils.runIt
fun main() = runIt(
testInput = """
30373
25512
65332
33549
35390
""".trimIndent(),
::part1,
testAnswerPart1 = 21,
::part2,
testAnswerPart2 = 8,
)
fun part1(input: String): Int {
val treeHeights = input.toSingleDigitIntGrid()
val rowCount = treeHeights.size
val columnCount = treeHeights[0].size
return treeHeights.indices.sumOf { r ->
if (r == 0 || r == rowCount - 1) columnCount
else treeHeights[r].indices.count { c ->
c == 0 || c == columnCount - 1 || run {
val height = treeHeights[r][c]
fun visibleLeft() = (c - 1 downTo 0).none { treeHeights[r][it] >= height }
fun visibleRight() = (c + 1 until columnCount).none { treeHeights[r][it] >= height }
fun visibleTop() = (r - 1 downTo 0).none { treeHeights[it][c] >= height }
fun visibleBottom() = (r + 1 until rowCount).none { treeHeights[it][c] >= height }
visibleLeft() || visibleRight() || visibleTop() || visibleBottom()
}
}
}
}
fun part2(input: String): Int {
val treeHeights = input.toSingleDigitIntGrid()
val rowCount = treeHeights.size
val columnCount = treeHeights[0].size
return treeHeights.indices.maxOf { r ->
treeHeights[r].indices.maxOf { c ->
val height = treeHeights[r][c]
val sceneryLeft = (c - 1 downTo 0).countUntil { treeHeights[r][it] >= height }
val sceneryRight = (c + 1 until columnCount).countUntil { treeHeights[r][it] >= height }
val sceneryTop = (r - 1 downTo 0).countUntil { treeHeights[it][c] >= height }
val sceneryBottom = (r + 1 until rowCount).countUntil { treeHeights[it][c] >= height }
sceneryLeft * sceneryRight * sceneryTop * sceneryBottom
}
}
}
fun String.toSingleDigitIntGrid() = lines()
.map { line -> IntArray(line.length) { line[it].digitToInt() } }
inline fun <T> Iterable<T>.countUntil(predicate: (T) -> Boolean): Int {
var count = 0
for (element in this) {
count++
if (predicate(element)) break
}
return count
}
| 0 | Kotlin | 0 | 0 | ee18157a24765cb129f9fe3f2644994f61bb1365 | 1,957 | advent-of-code-kotlin | Do What The F*ck You Want To Public License |
src/year2022/day07/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2022.day07
import readInput
fun main() {
fun getDirectorySize(input: List<String>): List<Pair<String, Int>> {
val v =
(input + listOf("$ cd \\")).asSequence().mapIndexedNotNull { index, s ->
when {
s.startsWith("$ cd") -> index to s.substring(5)
else -> null
}
}
.zipWithNext()
.map {
(it.first.second to it.second.second) to
input.subList(it.first.first, it.second.first)
.mapNotNull { it.split(" ").first().toIntOrNull() }.sum()
}
.fold(mutableListOf<Pair<String, Int>>()) { acc, pair ->
acc.also {
val previous = acc.lastOrNull()?.first ?: ""
val actualFolder = when (pair.first.first) {
".." -> previous.substring(0, previous.lastIndexOf("/"))
else -> "$previous/${pair.first.first}"
}
acc.add(actualFolder to pair.second)
}
}.toList().distinctBy { it.first }
return v.map { item -> item.first to v.filter { it.first.startsWith(item.first) }.sumOf { it.second } }
}
fun part1(input: List<String>): Int {
val map = getDirectorySize(input)
return map.filter { it.second <= 100000 }.sumOf { it.second }
}
fun part2(input: List<String>): Int {
val sz = getDirectorySize(input)
val directorySize = sz.sortedByDescending { it.second }
val needed = 30000000 - (70000000 - directorySize[0].second)
return directorySize.last { it.second > needed }.second
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("year2022/day07/test")
val expectedTest1 = 95437
val part1Test = part1(testInput)
check(part1Test == expectedTest1) { "expected $expectedTest1 but was $part1Test" }
val input = readInput("year2022/day07/input")
println(part1(input))
val expectedTest2 = 24933642
val part2Test = part2(testInput)
check(part2Test == expectedTest2) { "expected $expectedTest2 but was $part2Test" }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 2,361 | adventOfCode | Apache License 2.0 |
src/Day18.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | object Day18 {
const val EXPECTED_PART1_CHECK_ANSWER = 64
const val EXPECTED_PART2_CHECK_ANSWER = 58
}
fun main() {
val air = mutableMapOf<Point3D, Boolean>()
fun List<String>.parsePoints() =
map { line ->
val xyz = line.split(',')
Point3D(xyz[0].toInt(), xyz[1].toInt(), xyz[2].toInt())
}
fun Point3D.sides() =
listOf(
Triple(-1, 0, 0),
Triple(0, 1, 0),
Triple(1, 0, 0),
Triple(0, -1, 0),
Triple(0, 0, 1),
Triple(0, 0, -1),
).map { (xMove, yMove, zMove) ->
Point3D(x + xMove, y +yMove, z + zMove)
}
fun addToCache(points: Iterable<Point3D>, isAir: Boolean): Boolean {
points.forEach { air[it] = isAir }
return isAir
}
fun Point3D.outsideRange(pMin: Point3D, pMax: Point3D) = x < pMin.x || x > pMax.x || y < pMin.y || y > pMax.y || z < pMin.z || z > pMax.z
fun Point3D.isAir(points: List<Point3D>, pMin: Point3D, pMax: Point3D): Boolean {
air[this]?.let { return it }
val frontier = ArrayDeque(listOf(this))
val visited = mutableSetOf<Point3D>()
while (!frontier.isEmpty()) {
val current = frontier.removeFirst()
when {
!visited.add(current) -> continue
current in air -> return addToCache(visited, air.getValue(current))
current.outsideRange(pMin, pMax) -> return addToCache(visited, false)
else -> frontier.addAll(current.sides().filter { it !in points })
}
}
return addToCache(visited, true)
}
fun part1(input: List<String>): Int {
val points = input.parsePoints()
return points.sumOf { point ->
point.sides().count { it !in points }
}
}
fun part2(input: List<String>): Int {
val points = input.parsePoints()
val pMin = Point3D(points.minOf { it.x }, points.minOf { it.y }, points.minOf { it.z })
val pMax = Point3D(points.maxOf { it.x }, points.maxOf { it.y }, points.maxOf { it.z })
val result = points.sumOf { point ->
point.sides().filter { it !in points }.count { !it.isAir(points, pMin, pMax) }
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
check(part1(testInput) == Day18.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day18.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 2,673 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day03.kt | geodavies | 575,035,123 | false | {"Kotlin": 13226} | fun String.splitInHalf(): Pair<String, String> {
val numItems = length
return substring(0 until numItems / 2) to substring(numItems / 2 until numItems)
}
fun Pair<String, String>.findDuplicate(): Char {
val firstItems = first.toCharArray().toSet()
return second.toCharArray().find { firstItems.contains(it) }!!
}
fun calculatePriority(item: Char): Int = if (item.isUpperCase()) {
item.code - 38
} else {
item.code - 96
}
fun findCommonItem(group: List<String>): Char {
val allChars = mutableMapOf<Char, Int>()
group.forEach { contents ->
contents.toCharArray().toSet().forEach { item ->
val currentCount = allChars.getOrDefault(item, 0)
allChars[item] = currentCount + 1
}
}
return allChars.entries.find { it.value == 3 }!!.key
}
fun main() {
fun part1(input: List<String>) = input.map(String::splitInHalf)
.map(Pair<String, String>::findDuplicate)
.map { calculatePriority(it) }
.reduce { acc, i -> acc + i }
fun part2(input: List<String>): Int {
val groups = mutableListOf<MutableList<String>>()
input.forEachIndexed { idx, contents ->
if (idx % 3 == 0) {
groups.add(mutableListOf(contents))
} else {
groups[groups.size - 1].add(contents)
}
}
return groups.map { findCommonItem(it) }
.map { calculatePriority(it) }
.sumAll()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d04a336e412ba09a1cf368e2af537d1cf41a2060 | 1,754 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/Day12.kt | ekureina | 433,709,362 | false | {"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386} | fun main() {
fun String.isLargeCave(): Boolean = get(0).isUpperCase()
fun buildMap(input: List<String>): Map<String, List<String>> {
val connections = mutableMapOf<String, MutableList<String>>()
input.forEach { line ->
val (start, end) = line.split("-")
connections[start] = connections[start]?.also { list -> list.add(end) } ?: mutableListOf(end)
connections[end] = connections[end]?.also { list -> list.add(start) } ?: mutableListOf(start)
}
return connections
}
fun pathsFrom(source: String, connections: Map<String, List<String>>, visited: List<String> = listOf()): Int {
return if (source == "end") {
1
} else {
val newVisited = buildList {
addAll(visited)
add(source)
}
connections[source]!!
.filterNot { neighbor -> visited.contains(neighbor) && !neighbor.isLargeCave() }
.sumOf { neighbor ->
pathsFrom(neighbor, connections, newVisited)
}
}
}
fun pathsFromWithRepeat(
source: String,
connections: Map<String, List<String>>,
visited: List<String> = listOf(),
repeats: Int = 1
): Int {
return if (source == "end") {
1
} else {
val newVisited = buildList {
addAll(visited)
add(source)
}
val noRepeatPaths = connections[source]!!
.filterNot { neighbor -> visited.contains(neighbor) && !neighbor.isLargeCave() }
.sumOf { neighbor ->
pathsFromWithRepeat(neighbor, connections, newVisited, repeats)
}
val withRepeats = if (repeats > 0) {
connections[source]!!.filter { neighbor -> visited.contains(neighbor) && !neighbor.isLargeCave() && neighbor != "start" && neighbor != "end" }
.sumOf { neighbor ->
pathsFromWithRepeat(neighbor, connections, newVisited, repeats - 1)
}
} else {
0
}
noRepeatPaths + withRepeats
}
}
fun part1(input: List<String>): Int {
val connections = buildMap(input)
return pathsFrom("start", connections)
}
fun part2(input: List<String>): Int {
val connections = buildMap(input)
return pathsFromWithRepeat("start", connections)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 10) { "${part1(testInput)}" }
check(part2(testInput) == 36) { "${part2(testInput)}" }
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 391d0017ba9c2494092d27d22d5fd9f73d0c8ded | 2,858 | aoc-2021 | MIT License |
src/main/kotlin/dev/tasso/adventofcode/_2021/day08/Day08.kt | AndrewTasso | 433,656,563 | false | {"Kotlin": 75030} | package dev.tasso.adventofcode._2021.day08
import dev.tasso.adventofcode.Solution
class Day08 : Solution<Int> {
override fun part1(input: List<String>): Int {
return input.map { notesEntry -> notesEntry.split("|")[1].trim().split(" ")}
.sumOf { it.count { listOf(2,3,4,7).contains(it.length) } }
}
override fun part2(input: List<String>): Int {
//Split each note into signal patterns and output value by splitting on the '|'
val splitNotes = input.map{notesEntry -> notesEntry.split("|")}
val processedNotes = splitNotes.map { splitNote ->
//For each element of the note entry (signal patterns and output values)
splitNote.map { digits ->
//Get a list of digits
digits.trim().split(" ").map{ digit ->
//Break the digit into its component segments and sort to ensure consistent representation herein
digit.toCharArray().sorted()
}
}
}
return processedNotes.sumOf { noteEntry ->
val lookupTable = decodeLookupTable(noteEntry[0])
noteEntry[1].joinToString("") { outputDigit -> lookupTable[outputDigit].toString() }.toInt()
}
}
}
fun decodeLookupTable(signalPatternDigits : List<List<Char>>): Map<List<Char>, Int> {
//Knock out the easy number of segment based digits first
val characterToSegmentsMap = mutableMapOf(
1 to signalPatternDigits.single { it.size == 2 },
7 to signalPatternDigits.single { it.size == 3 },
4 to signalPatternDigits.single { it.size == 4 },
8 to signalPatternDigits.single { it.size == 7 },
)
//3 is the only 5 segment character that shares every segment of the digit 7
characterToSegmentsMap[3] = signalPatternDigits.single{it.size == 5 && (it intersect characterToSegmentsMap[7]!!).toTypedArray() contentEquals characterToSegmentsMap[7]!!.toTypedArray()}
//9 is the only 6 segment character that shares every segment of the digit 4
characterToSegmentsMap[9] = signalPatternDigits.single{it.size == 6 && (it intersect characterToSegmentsMap[4]!!).toTypedArray() contentEquals characterToSegmentsMap[4]!!.toTypedArray()}
//Now that 9 is decoded, 0 is the only 6 segment character that shares every segment of the digit 7
characterToSegmentsMap[0] = signalPatternDigits.single{it.size == 6 && it != characterToSegmentsMap[9]!! && (it intersect characterToSegmentsMap[7]!!).toTypedArray() contentEquals characterToSegmentsMap[7]!!.toTypedArray()}
//Now that 9 and 0 are decoded, 6 is the only 6 segment character remaining
characterToSegmentsMap[6] = signalPatternDigits.single{it.size == 6 && it != characterToSegmentsMap[9]!! && it !=characterToSegmentsMap[0]!!}
//5 is the only remaining 3 segment character the shares any segments with another number (6)
characterToSegmentsMap[5] = signalPatternDigits.single{it.size == 5 && (it intersect characterToSegmentsMap[6]!!).toTypedArray() contentEquals it.toTypedArray()}
//2 is the only character remaining not assigned
characterToSegmentsMap[2] = (signalPatternDigits subtract characterToSegmentsMap.values).single()
//Swap the keys and values so that the digit can be looked up by the segments
return characterToSegmentsMap.entries.associate { entry -> Pair(entry.value, entry.key)}
}
| 0 | Kotlin | 0 | 0 | daee918ba3df94dc2a3d6dd55a69366363b4d46c | 3,404 | advent-of-code | MIT License |
src/Day07.kt | touchman | 574,559,057 | false | {"Kotlin": 16512} | fun main() {
val input = readInput("Day07")
val hierarchy: Folder = createHierarchy(input)
val allFolders = mutableMapOf<String, Long>()
findAllFoldersWithFileSize(allFolders, hierarchy)
addSizeOfSubFolders(allFolders)
fun part1(allFolders: MutableMap<String, Long>): Long =
allFolders.values.filter { it <= 100_000 }.sum()
fun part2(allFolders: MutableMap<String, Long>): Long {
val unusedSpace = 70_000_000 - allFolders["/root"]!!
val requiredMemoryForDelete = 30_000_000 - unusedSpace
return allFolders.values.sortedDescending()
.let { sorted ->
val indexOfTheClosest = sorted.mapIndexed { index, l -> index to l - requiredMemoryForDelete }
.filter { it.second > 0 }
.minByOrNull { pair -> pair.second }!!.first
sorted[indexOfTheClosest]
}
}
println(part1(allFolders))
println(part2(allFolders))
}
fun createHierarchy(input: List<String>): Folder {
val hierarchy = Folder("root", mutableListOf())
var currentPointer: Folder? = hierarchy
for (i in 1..input.lastIndex) {
val line = input[i]
when {
line.contains("$ cd") -> {
currentPointer = if (line.contains("..")) {
currentPointer?.parent
} else {
currentPointer?.children?.first { it.name == line.split(" ")[2] }
}
}
line == "$ ls" -> {}
else -> {
if (line.contains("dir")) {
createFolder(line, currentPointer)
} else {
createFileInFolder(line, currentPointer)
}
}
}
}
return hierarchy
}
fun findAllFoldersWithFileSize(folderNameToSize: MutableMap<String, Long>, pointer: Folder, incrementingName: String = ""): Pair<String, Long> {
val currentName = incrementingName + "/" + pointer.name
pointer.children.forEach {
val (name, size) = findAllFoldersWithFileSize(folderNameToSize, it, currentName)
folderNameToSize[name] = size
}
if (currentName == "/root") {
folderNameToSize[currentName] = pointer.files.sumOf { it.size }
}
return currentName to pointer.files.sumOf { it.size }
}
fun addSizeOfSubFolders(allFolders: MutableMap<String, Long>) {
allFolders.forEach { (t, u) ->
val sizeOfAllSubFolders = allFolders.keys
.filter { it.contains(t) && t != it && it.substringAfter(t).split("/").size == 2 }
.map { allFolders[it]!! }
.takeIf { it.isNotEmpty() }
?.reduce { acc, l -> acc + l }
sizeOfAllSubFolders?.let {
if (sizeOfAllSubFolders != 0L) {
allFolders[t] = u + sizeOfAllSubFolders
}
}
}
}
fun createFileInFolder(line: String, currentPointer: Folder?) {
line.split(" ").let {
currentPointer?.files?.add(File(it[1], it[0].toLong()))
}
}
fun createFolder(line: String, currentPointer: Folder?): Folder {
val folder = Folder(line.substringAfter(" "), mutableListOf()).apply {
parent = currentPointer
}
currentPointer?.children?.add(folder)
return folder
}
data class Folder(
val name: String,
val files: MutableList<File>
) {
var parent: Folder? = null
val children: MutableList<Folder> = mutableListOf()
}
data class File(
val name: String,
val size: Long,
) | 0 | Kotlin | 0 | 0 | 4f7402063a4a7651884be77bb9e97828a31459a7 | 3,517 | advent-of-code-2022 | Apache License 2.0 |
src/Day18.kt | esp-er | 573,196,902 | false | {"Kotlin": 29675} | package patriker.day18
import patriker.utils.*
data class Pos3(val x: Int, val y: Int, val z: Int)
val Pos3.adjacentPositions: List<Pos3>
get() = listOf(Pos3(x - 1, y, z ), Pos3(x + 1, y, z ) , Pos3(x, y - 1, z ) , Pos3(x, y + 1, z ), Pos3(x, y, z - 1), Pos3(x, y , z + 1))
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
val input = readInput("Day18_input")
//check(solvePart1(testInput) == 64)
println(solvePart1(testInput))
println(solvePart1(input))
println(solvePart2(testInput))
println(solvePart2(input))
}
fun inputToSet(input: List<String>): HashSet<Pos3>{
val set = HashSet<Pos3>()
input.forEach{line ->
val (xstr, ystr, zstr) = line.split(",")
set.add(Pos3( xstr.toInt(), ystr.toInt(), zstr.toInt()))
}
return set
}
fun solvePart1(input: List<String>): Int{
val lavaPositions = inputToSet(input)
return surfaceArea(lavaPositions)
}
fun surfaceArea(positions: HashSet<Pos3>): Int{
val surfaceArea = positions.sumOf {pos ->
val adjCount = pos.adjacentPositions.count{
positions.contains(it)
}
6 - adjCount
}
return surfaceArea
}
fun Pos3.outOfBounds(bounds: Bounds3): Boolean{
return x !in bounds.xRange || y !in bounds.yRange || z !in bounds.zRange
}
data class Bounds3(val xRange: IntRange, val yRange: IntRange, val zRange: IntRange)
fun Pos3.hasWayOut(lavaPositions: HashSet<Pos3>, bounds: Bounds3, visited: HashSet<Pos3> = HashSet<Pos3>(), toVisit: HashSet<Pos3> = HashSet()): Boolean {
if(this.outOfBounds(bounds))
return true
val adjPositions = this.adjacentPositions
val toVisit = adjPositions.filter{it !in lavaPositions && it !in visited}
if(toVisit.isEmpty())
return false
visited.addAll(toVisit + this)
return toVisit.any { p -> p.hasWayOut(lavaPositions, bounds, visited) }
}
fun solvePart2(input: List<String>): Int{
val lavaPositions = inputToSet(input)
val xRange = lavaPositions.minOf{it.x}..lavaPositions.maxOf{it.x}
val yRange = lavaPositions.minOf{it.y}..lavaPositions.maxOf{it.y}
val zRange = lavaPositions.minOf{it.z}..lavaPositions.maxOf{it.z}
val emptyPositions = HashSet<Pos3>()
emptyPositions.addAll (
xRange.flatMap { x ->
yRange.flatMap { y ->
zRange.map { z ->
Pos3(x, y, z)
}
}
}.filter { it !in lavaPositions }
)
val bubblePositions = emptyPositions.filterNot{
it.hasWayOut(lavaPositions, Bounds3(xRange, yRange, zRange))
}
//val bubbleSurface = surfaceArea( bubblePositions.toHashSet())
val bubbleSurface = surfaceArea( bubblePositions.toHashSet())
return surfaceArea(lavaPositions) - bubbleSurface
} | 0 | Kotlin | 0 | 0 | f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362 | 2,856 | aoc2022 | Apache License 2.0 |
src/main/kotlin/dec7/Main.kt | dladukedev | 318,188,745 | false | null | package dec7
data class Bag(
val color: String,
val count: Int
)
data class BagRule(
val color: String,
val bagsInside: List<Bag>
)
fun getBagRules(input: String): List<BagRule> {
return input.lines()
.filter { it.isNotEmpty() }
.map {
val color = it.split(" ").take(2).joinToString(" ")
val bags = it.split(" contain ")
.last()
.split(", ")
.filter { str -> str != "no other bags." }
.map {str ->
val bagCount = str.split(" ").first().toInt()
val bagColor = str.split(" ").subList(1, 3).joinToString(" ")
Bag(bagColor, bagCount)
}
BagRule(
color,
bags
)
}
}
fun countBags(bagColor: String, bagRules: List<BagRule>): Int {
val bagRule = bagRules.single { it.color == bagColor }
if (bagRule.bagsInside.isEmpty()) {
return 1
}
return 1 + bagRule.bagsInside.sumBy {
it.count * countBags(it.color, bagRules)
}
}
fun getBagCountInside(bagColor: String, bagRules: List<BagRule>): Int {
return countBags(bagColor, bagRules) - 1
}
fun getBagsThatCanContain(bagColor: String, bagRules: List<BagRule>, accum: List<BagRule> = emptyList()): List<BagRule> {
val bagsThatCanHoldColor = bagRules.filter { it.bagsInside.any { bag -> bag.color == bagColor} }
val newColors = bagsThatCanHoldColor.filter { !accum.contains(it) }
if(newColors.isEmpty()) {
return accum
}
val newList = accum + newColors
return newColors.map {
getBagsThatCanContain(it.color, bagRules, newList)
}.flatten()
.distinctBy { it.color }
}
fun main() {
val bagRules = getBagRules(input)
println("------------ PART 1 ------------")
val bags = getBagsThatCanContain("shiny gold", bagRules).count()
println("result $bags") // 370
println("------------ PART 2 ------------")
val bagCount = getBagCountInside("shiny gold", bagRules)
println("result $bagCount") // 25300
}
| 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 2,120 | advent-of-code-2020 | MIT License |
src/main/kotlin/days/Day5.kt | MisterJack49 | 729,926,959 | false | {"Kotlin": 31964} | package days
class Day5 : Day(5) {
override fun partOne(): Any {
val almanac = inputString.split(Regex("\\r\\n\\r\\n"))
val seeds = almanac[0].split(":")[1].split(" ").filterNot { it.isEmpty() }.map { it.toLong() }
val mappers = almanac.drop(1)
.mapIndexed { idx, mapper ->
mapper.split(Regex("\\r\\n"))
.filter { it.isNotEmpty() }
.drop(1)
.map {
it.split(" ")
}
.map {
Range(it[0].toLong(), it[1].toLong(), it[2].toLong())
}.run { Mapper(Category.values()[idx], Category.values()[idx + 1], this) }
}
return seeds.minOf { seed ->
mappers.findLocation(seed)
}
}
override fun partTwo(): Any {
val almanac = inputString.split(Regex("\\r\\n\\r\\n"))
val seedRanges = almanac[0].split(":")[1]
.split(" ")
.filterNot { it.isEmpty() }
.map { it.toLong() }
.chunked(2)
val mappers = almanac.drop(1)
.mapIndexed { idx, mapper ->
mapper.split(Regex("\\r\\n"))
.filter { it.isNotEmpty() }
.drop(1)
.map {
it.split(" ")
}
.map {
Range(it[0].toLong(), it[1].toLong(), it[2].toLong())
}.run { Mapper(Category.values()[idx], Category.values()[idx + 1], this) }
}
return seedRanges.minOf {
mappers.findMin(it.first(), it.last())
}
}
}
private fun List<Mapper>.findMin(start: Long, length: Long): Long {
if (length == 1L) return minOf(findLocation(start), findLocation(start + 1))
val stepSize = length / 2
val middle = start + stepSize
val startLocation = findLocation(start)
val middleLocation = findLocation(middle)
val endLocation = findLocation(start + length)
var foundMin = Long.MAX_VALUE
if (startLocation + stepSize != middleLocation) {
foundMin = findMin(start, stepSize)
}
if (middleLocation + (length - stepSize) != endLocation) {
foundMin = minOf(foundMin, findMin(middle, length - stepSize))
}
return foundMin
}
private fun List<Mapper>.findLocation(seed: Long) =
fold(seed) { acc, mapper ->
mapper.convert(acc)
}
private data class Range(val destination: Long, val source: Long, val size: Long) {
fun isMapping(value: Long): Boolean =
(source until source + size).contains(value)
fun convert(value: Long): Long =
if (isMapping(value).not()) value
else destination + (value - source)
}
private data class Mapper(val from: Category, val to: Category, val ranges: List<Range>) {
fun convert(value: Long): Long =
ranges.firstOrNull { it.isMapping(value) }?.convert(value) ?: value
}
private enum class Category {
Seed, Soil, Fertilizer, Water, Light, Temperature, Humidity, Location
}
| 0 | Kotlin | 0 | 0 | 807a6b2d3ec487232c58c7e5904138fc4f45f808 | 3,116 | AoC-2023 | Creative Commons Zero v1.0 Universal |
src/day05/Day05.kt | wickenico | 573,158,084 | false | {"Kotlin": 6839} | fun main() {
fun part1(stacks: List<ArrayDeque<Char>>, steps: List<Step>): String {
steps.map { step -> repeat(step.quantity) { stacks[step.target].addFirst(stacks[step.source].removeFirst()) } }
return stacks.map { it.first() }.joinToString(separator = "")
}
fun part2(stacks: List<ArrayDeque<Char>>, steps: List<Step>): String {
steps.map { step ->
stacks[step.source].subList(0, step.quantity).asReversed()
.map { stacks[step.target].addFirst(it) }
.map { stacks[step.source].removeFirst() }
}
return stacks.map { it.first() }.joinToString(separator = "")
}
val input = readInput("day05")
val numberOfStacks = input.dropWhile { it.contains("[") }.first().split(" ").filter { it.isNotBlank() }.maxOf { it.toInt() }
val stacks = List(numberOfStacks) { ArrayDeque<Char>() }
val steps = mutableListOf<Step>()
input.filter { it.contains("[") }
.map { line ->
line
.mapIndexed { index, char -> if (char.isLetter()) stacks[index / 4].addLast(line[index]) }
}
input.filter { it.contains("move") }.map { steps.add(Step.of(it)) }
println(part1(stacks.map { ArrayDeque(it) }.toList(), steps))
println(part2(stacks, steps))
}
data class Step(val quantity: Int, val source: Int, val target: Int) {
companion object {
fun of(line: String): Step {
return line.split(" ").filterIndexed { index, _ -> index % 2 == 1 }.map { it.toInt() }.let { Step(it[0], it[1] - 1, it[2] - 1) }
}
}
}
| 0 | Kotlin | 0 | 0 | bc587f433aa38c4d745c09d82b7d231462f777c8 | 1,596 | advent-of-code-kotlin | Apache License 2.0 |
src/day12/Day12.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day12
import readInput
fun Array<IntArray>.hasIndices(indices: Pair<Int, Int>) =
indices.first >= 0 && indices.first < this.size && indices.second >= 0 && indices.second < this[indices.first].size
fun Array<IntArray>.get(indices: Pair<Int, Int>) = this[indices.first][indices.second]
fun Pair<Int, Int>.minusFirst(amount: Int = 1) = Pair(this.first - amount, this.second)
fun Pair<Int, Int>.plusFirst(amount: Int = 1) = Pair(this.first + amount, this.second)
fun Pair<Int, Int>.minusSecond(amount: Int = 1) = Pair(this.first, this.second - amount)
fun Pair<Int, Int>.plusSecond(amount: Int = 1) = Pair(this.first, this.second + amount)
fun main() {
fun bfs(
start: Pair<Int, Int>,
map: Array<IntArray>,
endCondition: (pos: Pair<Int, Int>, elevation: Int) -> Boolean
): Int {
val visited = mutableSetOf(start)
val queue = mutableListOf(Pair(0, start))
while (queue.isNotEmpty()) {
val (steps, next) = queue.removeFirst()
if (endCondition(next, map.get(next))) {
return steps
}
val toCheck = listOf(next.minusFirst(), next.plusFirst(), next.minusSecond(), next.plusSecond())
for (check in toCheck) {
if (map.hasIndices(check) && !visited.contains(check) && map.get(check) - map.get(next) <= 1) {
queue.add(Pair(steps + 1, check))
visited.add(check)
}
}
}
return Int.MAX_VALUE
}
fun part1(input: Triple<Pair<Int, Int>, Pair<Int, Int>, Array<IntArray>>): Int =
bfs(input.first, input.third) { pos, _ ->
pos == input.second
}
fun part2(input: Triple<Pair<Int, Int>, Pair<Int, Int>, Array<IntArray>>): Int = bfs(
input.second,
input.third.map { it.map { -it }.toIntArray() }.toTypedArray()
) { _, elevation ->
elevation == 0
}
fun preprocess(input: List<String>): Triple<Pair<Int, Int>, Pair<Int, Int>, Array<IntArray>> {
var start = Pair(0, 0)
var end = Pair(0, 0)
val map = input.mapIndexed { i, row ->
row.mapIndexed { j, char ->
when (char) {
'S' -> 'a'.code.also { start = Pair(i, j) }
'E' -> 'z'.code.also { end = Pair(i, j) }
else -> char.code
} - 'a'.code
}.toIntArray()
}.toTypedArray()
return Triple(start, end, map)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(12, true)
check(part1(preprocess(testInput)) == 31)
val input = readInput(12)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) == 29)
println(part2(preprocess(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 2,832 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | data class Scanner(val center: Vector2, val beacon: Vector2)
fun main() {
val matcher = ".+?x=(?<x1>-?\\d+), y=(?<y1>-?\\d+).+x=(?<x2>-?\\d+), y=(?<y2>-?\\d+)".toRegex()
fun parse(input: List<String>): List<Scanner> {
val res = emptyList<Scanner>().toMutableList()
for (line in input) {
val groups = matcher.matchEntire(line)!!.groups
val x1 = groups["x1"]!!.value.toInt()
val y1 = groups["y1"]!!.value.toInt()
val x2 = groups["x2"]!!.value.toInt()
val y2 = groups["y2"]!!.value.toInt()
res.add(Scanner(Vector2(x1, y1), Vector2(x2, y2)))
}
return res
}
fun scanLine(scanners: List<Scanner>, targetY: Int): Pair<Set<Vector2>, Set<Int>> {
val segments = mutableSetOf<Vector2>()
val exclude = scanners.
filter { it.beacon.second == targetY }.
map { it.beacon.first }.toSet()
for (scanner in scanners) {
val dist = scanner.center.manhattanDist(scanner.beacon)
val tmp = if (scanner.center.second < targetY) {
(dist - targetY + scanner.center.second) shl 1
} else {
(dist + targetY - scanner.center.second) shl 1
}
if (kotlin.math.abs(targetY - scanner.center.second) <= dist) {
val deltaX = (tmp shr 1)
val stX = scanner.center.first - deltaX
val endX = scanner.center.first + deltaX
segments.add(Vector2(stX, endX))
}
}
return Pair(segments, exclude)
}
fun part1(input: List<String>, targetY: Int): Int {
val res = scanLine(parse(input), targetY)
val segments = res.first.sortedBy { it.first }
return segments.last().second - segments.first().first - res.second.size + 1
}
fun findGap(segments: Set<Vector2>): Int? {
var maxSoFar = Int.MIN_VALUE
for ((cur, next) in segments.sortedBy { it.first }.zipWithNext()) {
if (cur.second > maxSoFar) {
maxSoFar = cur.second
}
if (next.first > maxSoFar) {
return cur.second + 1
}
}
return null
}
fun part2(input: List<String>, maxCoord: Int): Long? {
val parsed = parse(input)
return (0..maxCoord).map{
val res = scanLine(parsed, it)
val gapX = findGap(res.first)
if (gapX != null && !res.second.contains(gapX))
4_000_000.toLong() * gapX + it
else
null
}.firstNotNullOf { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011.toLong())
val input = readInput("Day15")
println(part1(input, 2_000_000))
println(part2(input, 4_000_000))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 2,980 | aoc2022 | Apache License 2.0 |
src/day07/Day07.kt | lpleo | 572,702,403 | false | {"Kotlin": 30960} | package day07
import TreeNode
import readInput
class FileSystemItem(val name: String, val type: Char, var dimension: Int) {
fun isDirectory() = type == 'D'
fun isFile() = type == 'F'
}
fun main() {
fun calculateDimension(node: TreeNode<FileSystemItem>): Int {
return node.getChildren().sumOf { child -> if (child.value.isFile()) child.value.dimension else calculateDimension(child) }
}
fun createTree(input: List<String>): TreeNode<FileSystemItem> {
val homeNode: TreeNode<FileSystemItem> = TreeNode(FileSystemItem("/", 'D', 0))
var actualNode = homeNode
input.subList(2, input.size).forEach { command ->
if (command.startsWith("dir ")) {
val directoryName = command.split(" ")[1]
actualNode.addChild(TreeNode(FileSystemItem(directoryName, 'D', 0)));
} else if (command.matches(Regex("[0-9]+ (.+)"))) {
val filename = command.split(" ")[1]
val filesize = command.split(" ")[0].toInt()
actualNode.addChild(TreeNode(FileSystemItem(filename, 'F', filesize)))
} else if (command == "\$ cd ..") {
actualNode = actualNode.getParent()!!
} else if (command.startsWith("\$ cd")) {
val parent = actualNode
actualNode = actualNode.getChild { child -> child.value.name == command.split(" ")[2] }!!
actualNode.setParent(parent);
}
}
return homeNode
}
fun getDirectoryDimensions(node: TreeNode<FileSystemItem>, folderList: MutableList<Pair<String, Int>>): MutableList<Pair<String, Int>> {
folderList.add(Pair(node.value.name, calculateDimension(node)))
node.getChildren().filter { child -> child.value.isDirectory() }.forEach { child -> getDirectoryDimensions(child, folderList) }
return folderList;
}
fun part1(input: List<String>): Int {
val homeNode: TreeNode<FileSystemItem> = createTree(input)
return getDirectoryDimensions(homeNode, ArrayList())
.map { directoryDimension -> directoryDimension.second }
.filter { directoryDimension -> directoryDimension < 100000 }
.sum()
}
fun part2(input: List<String>): Int {
val homeNode: TreeNode<FileSystemItem> = createTree(input)
val spaceToFree = 30000000 - (70000000 - calculateDimension(homeNode))
return getDirectoryDimensions(homeNode, ArrayList())
.map { directoryDimension -> directoryDimension.second }
.filter { directoryDimension -> (directoryDimension - spaceToFree) > 0 }
.minBy { directoryDimension -> directoryDimension - spaceToFree }
}
check(part1(readInput("files/Day07_test")) == 95437)
check(part2(readInput("files/Day07_test")) == 24933642)
val input = readInput("files/Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 115aba36c004bf1a759b695445451d8569178269 | 2,967 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} |
private fun createOperation(txt: String): (Long) -> Long {
val (a, op, b) = txt.substringAfter("new = ").split(' ')
check(a=="old")
val const = b.toIntOrNull()
return when(op[0]){
'+' -> if (const==null) { old -> old + old } else { old -> old + const }
'*' -> if (const==null) { old -> old * old } else { old -> old * const }
else -> error("Invalid operation $op")
}
}
private class Monkey(input: List<String>) {
var items = input[0].split(", ").map { it.toInt() }.toMutableList()
val operation = createOperation(input[1])
val modulo = input[2].substringAfter("divisible by ").toInt()
val ifTrue = input[3].substringAfter("throw to monkey ").toInt()
val ifFalse = input[4].substringAfter("throw to monkey ").toInt()
var inspected = 0
fun action(monkeys: List<Monkey>, divideBy: Int, mod: Int) {
items.forEach {
val level = (( operation(it.toLong()) / divideBy ) % mod).toInt()
monkeys[if (level % modulo == 0) ifTrue else ifFalse]
.items.add(level)
}
inspected += items.size
items.clear()
}
}
private fun go(lines: List<String>, divideBy: Int, rounds: Int): Long {
val monkeys = lines.splitBy { it.isBlank() }.map{ Monkey(it.drop(1).map { ln -> ln.substringAfter(": ") }) }
val mod = monkeys.map { it.modulo }.reduce(Int::times)
repeat(rounds) {
monkeys.forEach { it.action(monkeys,divideBy,mod) }
}
val (max1,max2) = monkeys.map { it.inspected }.sortedDescending()
return max1.toLong() * max2
}
private fun part1(lines: List<String>) = go(lines, 3, 20)
private fun part2(lines: List<String>) = go(lines, 1, 10000)
fun main() {
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input)) // 64032
println(part2(input)) // 12729522272
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 1,954 | aoc2022 | Apache License 2.0 |
src/year_2022/day_02/Day02.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_02
import readInput
enum class Shape(val letters: List<Char>, private val pointValue: Int) {
ROCK(listOf('A', 'X'), 1),
PAPER(listOf('B', 'Y'), 2),
SCISSORS(listOf('C', 'Z'),3),
;
companion object {
fun fromChar(letter: Char): Shape {
return values().first { shape ->
shape.letters.contains(letter)
}
}
}
fun result(other: Shape): Int {
var score = pointValue
when {
// tie = 3
this == other -> score += 3
// victories = 6
(this == ROCK && other == SCISSORS)
|| (this == PAPER && other == ROCK)
|| (this == SCISSORS && other == PAPER) -> score += 6
// loss = 0
else -> { /* no-op */ }
}
return score
}
}
enum class Result(val letter: Char) {
LOSS('X'),
DRAW('Y'),
WIN('Z'),
;
companion object {
fun fromChar(letter: Char): Result {
return Result.values().first { shape ->
shape.letter == letter
}
}
}
}
data class Round(
val elfShape: Shape,
val myShape: Shape
) {
val myRoundResult: Int = myShape.result(elfShape)
}
data class RequiredOutcomeRound(
val elfShape: Shape,
val requiredResult: Result
) {
private val myShape: Shape get() {
return when (requiredResult) {
Result.WIN -> {
when (elfShape) {
Shape.ROCK -> Shape.PAPER
Shape.PAPER -> Shape.SCISSORS
Shape.SCISSORS -> Shape.ROCK
}
}
Result.LOSS -> {
when (elfShape) {
Shape.ROCK -> Shape.SCISSORS
Shape.PAPER -> Shape.ROCK
Shape.SCISSORS -> Shape.PAPER
}
}
Result.DRAW -> elfShape
}
}
val myRoundResult: Int = myShape.result(elfShape)
}
object Day02 {
/**
* @return Total Score for all rounds
*/
fun solutionOne(roundsText: List<String>): Int {
return roundsText
.map { text ->
Round(
elfShape = Shape.fromChar(text[0]),
myShape = Shape.fromChar(text[2])
)
}
.sumOf { round ->
round.myRoundResult
}
}
/**
* @return Total score from updated rule book
*/
fun solutionTwo(roundsText: List<String>): Int {
return roundsText
.map { text ->
RequiredOutcomeRound(
elfShape = Shape.fromChar(text[0]),
requiredResult = Result.fromChar(text[2])
)
}
.sumOf { round ->
round.myRoundResult
}
}
}
fun main() {
val roundsText = readInput("year_2022/day_02/Day02.txt")
val solution1 = Day02.solutionOne(roundsText)
println("Solution 1: Total Score: $solution1")
val solution2 = Day02.solutionTwo(roundsText)
println("Solution 2: Total Score: $solution2")
}
| 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 3,189 | advent_of_code | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day17.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
import java.util.*
fun main() {
val input = readInput(2023, 17).readLines()
part1(input)
part2(input)
}
private fun part1(grid: List<String>) = println(shortestExit(grid, 1, 3))
private fun part2(grid: List<String>) = println(shortestExit(grid, 4, 10))
private fun shortestExit(grid: List<String>, min: Int, max: Int): Int {
val start = Index(0, 0)
val end = Index(grid[0].lastIndex, grid.lastIndex)
val dx = intArrayOf(1, 0, -1, 0)
val dy = intArrayOf(0, 1, 0, -1)
val plane = List(grid.size) { IntArray(grid[0].length) { Int.MAX_VALUE } }
val queue = PriorityQueue<ClumsyPath> { a, b -> a.cost - b.cost }
queue.offer(ClumsyPath(start, Index(0, 0), 0, 0))
val visited = hashSetOf<Triple<Index, Index, Int>>()
while (queue.isNotEmpty()) {
val (to, direction, directionCount, cost) = queue.poll()
plane[to.y][to.x] = cost
if (to == end) break
dy.indices.forEach { i ->
val nextDirection = Index(dx[i], dy[i])
val multiplier = if (direction == nextDirection) 1 else min
val next = Index(to.x + dx[i] * multiplier, to.y + dy[i] * multiplier)
plane.getOrNull(next.y)?.getOrNull(next.x) ?: return@forEach
if (nextDirection == Index(direction.x * -1, direction.y * -1)) return@forEach
val newCount = if (direction == nextDirection) directionCount + 1 else multiplier
if (newCount > max) return@forEach
if (!visited.add(Triple(next, nextDirection, newCount))) return@forEach
var moves = '0' - grid[to.y][to.x]
for (x in minOf(next.x, to.x)..maxOf(next.x, to.x)) for (y in minOf(next.y, to.y)..maxOf(next.y, to.y)) {
moves += grid[y][x] - '0'
}
queue.add(ClumsyPath(next, nextDirection, newCount, cost + moves))
}
}
return plane[end.y][end.x]
}
private data class ClumsyPath(val to: Index, val direction: Index, val directionCounter: Int, val cost: Int)
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 2,105 | adventofcode | Apache License 2.0 |
src/year_2023/day_15/Day15.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2023.day_15
import readInput
object Day15 {
/**
*
*/
fun solutionOne(text: List<String>): Int {
val values = parseInput(text).map { sequence ->
var currValue = 0
sequence.forEach { char ->
currValue += char.code
currValue *= 17
currValue %= 256
}
sequence to currValue
}
// values.forEach { println("${it.first} becomes ${it.second}") }
return values.sumOf { it.second }
}
data class Sequence(
val boxNumber: Int,
val label: String,
val modifier: Char,
val focalLength: Int?
)
/**
*
*/
fun solutionTwo(text: List<String>): Int {
val sequences = parseInput(text).map { sequence ->
var boxNumber = 0
val label = sequence.split("=").first().split("-").first()
label.forEach { char ->
boxNumber += char.code
boxNumber *= 17
boxNumber %= 256
}
val focalLength = try {
sequence.split("=").last().split("-").last().toInt()
} catch(e: Exception) {
null
}
Sequence(
boxNumber,
label,
if (sequence.contains("=")) '=' else '-',
focalLength
)
}
// map<BoxNumber, List<Label, Focal>
val map = mutableMapOf<Int, MutableList<Sequence>>()
sequences.forEach { sequence ->
if (map.containsKey(sequence.boxNumber)) {
val box = map[sequence.boxNumber]!!
if (sequence.modifier == '=') {
val exists = box.indexOfFirst { it.label == sequence.label }
if (exists == -1) {
box.add(sequence)
} else {
box[exists] = sequence
}
} else {
val exists = box.indexOfFirst { it.label == sequence.label }
if (exists > -1) {
box.removeAt(exists)
}
}
} else {
map[sequence.boxNumber] = mutableListOf(sequence)
}
}
return map.toList()
.sortedBy { (boxNumber, _) -> boxNumber }
.sumOf { (boxNumber, lenses) ->
lenses.sumOf { lense ->
(boxNumber + 1) * (lenses.indexOf(lense) + 1) * lense.focalLength!!
}
}
}
private fun parseInput(text: List<String>): List<String> {
val sequences = mutableListOf<String>()
text.forEach {
sequences.addAll(it.replace("\n", "").split(","))
}
return sequences
}
}
fun main() {
val text = readInput("year_2023/day_15/Day15.txt")
val solutionOne = Day15.solutionOne(text)
println("Solution 1: $solutionOne")
val solutionTwo = Day15.solutionTwo(text)
println("Solution 2: $solutionTwo")
}
| 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 3,115 | advent_of_code | Apache License 2.0 |
src/Day03.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | fun main() {
fun part1(input: List<String>): Long {
return input.mapIndexed { i, line ->
var observed = ""
var partNumber = false
var sum = 0L
line.forEachIndexed { j, char ->
if (char.isDigit()) {
observed += char
partNumber = partNumber || input.isAdjacentToSymbol(i, j)
} else {
if (partNumber) sum += observed.toLong()
observed = ""
partNumber = false
}
}
if (partNumber) sum + observed.toLong() else sum
}.sum()
}
fun part2(input: List<String>): Long {
val partNumberPositions = input.flatMapIndexed { i, line ->
var observed = ""
var partNumber = false
val positions = mutableListOf<EngineNumber>()
line.forEachIndexed { j, char ->
if (char.isDigit()) {
observed += char
partNumber = partNumber || input.isAdjacentToSymbol(i, j)
} else {
if (partNumber) positions.add(
EngineNumber(observed.toLong(), i, (j - observed.length) until j)
)
observed = ""
partNumber = false
}
}
val columns = line.length
if (partNumber) positions.add(EngineNumber(observed.toLong(), i, (columns - observed.length) until columns))
positions
}
return input.mapIndexed { i, line ->
line.mapIndexed secondIndexed@{ j, char ->
if (char != '*') return@secondIndexed 0L
val components = partNumberPositions.filter { it.row in (i - 1 .. i + 1) && it.columns.intersects(j - 1..j + 1) }
if (components.size == 2) {
val (first, second) = components
first.value * second.value
} else {
0L
}
}.sum()
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 4361L)
check(part2(testInput) == 467835L)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun List<String>.isAdjacentToSymbol(i: Int, j: Int): Boolean {
val adjacentPositions = listOf(
i - 1 to j - 1,
i - 1 to j,
i - 1 to j + 1,
i to j - 1,
i to j + 1,
i + 1 to j - 1,
i + 1 to j,
i + 1 to j + 1,
).filter { (x, y) -> x >= 0 && y >= 0 && x < size && y < get(x).length }
return adjacentPositions.any { (x, y) -> get(x)[y].let { !it.isDigit() && it != '.' } }
}
private data class EngineNumber(val value: Long, val row: Int, val columns: ClosedRange<Int>)
private fun ClosedRange<Int>.intersects(other: ClosedRange<Int>): Boolean {
return start in other || other.start in this
} | 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 3,141 | aoc-2022-in-kotlin | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day07.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val input = readInput(2023, 7).readLines()
part1(input)
part2(input)
}
private fun part1(input: List<String>) {
val hands = input.map { Hand.of(it, withJoker = false) }
solution(hands)
}
private fun part2(input: List<String>) {
val hands = input.map { Hand.of(it, withJoker = true) }
solution(hands)
}
private fun solution(hands: List<Hand>) {
val sorted = hands.sortedWith(compareBy(Hand::type, Hand::power))
val score = sorted.withIndex().fold(0) { acc, n -> acc + (n.index + 1) * n.value.bid }
println(score)
}
private data class Hand(val power: Int, val type: Int, val bid: Int) {
companion object {
// '2' to 'A' as a mod-14 number system
private val POWER = mapOf(
'*' to 0, // Placeholder for Joker
'2' to 1, '3' to 2, '4' to 3, '5' to 4, '6' to 5, '7' to 6, '8' to 7, '9' to 8,
'T' to 9, 'J' to 10, 'Q' to 11, 'K' to 12, 'A' to 13,
)
fun of(line: String, withJoker: Boolean): Hand {
val (deal, bid) = line.split(" ")
val frequency = hashMapOf<Char, Int>()
var power = 0
for (char in deal) {
frequency[char] = frequency.getOrDefault(char, 0) + 1
val charPower = if (char == 'J' && withJoker) 0 else POWER.getValue(char)
power = power * 14 + charPower
}
val type = frequency.evaluateType(withJoker)
return Hand(power, type, bid.toInt())
}
private fun MutableMap<Char, Int>.evaluateType(withJoker: Boolean): Int {
val jCount = getOrDefault('J', 0)
if (withJoker && jCount > 0) {
remove('J')
if (isEmpty()) return jCount * jCount
val (k, v) = maxBy { (_, v) -> v }
this[k] = v + jCount
}
return values.fold(0) { acc, f -> acc + f * f }
}
}
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 2,048 | adventofcode | Apache License 2.0 |
src/main/kotlin/challenges/Day03.kt | mledl | 725,995,129 | false | {"Kotlin": 66471} | package challenges
class Day03(private val input: List<String>) {
private val offset = input[0].length + 1
private val inputStr = input.fold("") { acc, s -> acc.plus("$s.") }
private val regex = "\\d+".toRegex()
fun getPart1(): Int = calcRanges(inputStr, offset, input.size).filter { pair -> pair.second.any { !isDigitOrDot(inputStr[it]) } }.sumOf { it.first }
fun getPart2(): Int {
var sum = 0
val ranges = input.map { regex.findAll(it).flatMap { match -> match.range.toList().map { it to match.value.toInt() } }.toMap() }
for ((lineIdx, line) in input.withIndex()) {
var gearIdx = line.indexOf('*')
while (gearIdx >= 0) {
val factors = arrayListOf<Int>()
// check line above
if (lineIdx > 0) {
if (gearIdx > 0) ranges[lineIdx - 1][gearIdx - 1]?.let { factors.add(it) }
if (ranges[lineIdx - 1][gearIdx - 1] != ranges[lineIdx - 1][gearIdx]) ranges[lineIdx - 1][gearIdx]?.let { factors.add(it) }
if (gearIdx < line.length && ranges[lineIdx - 1][gearIdx] != ranges[lineIdx - 1][gearIdx + 1]) ranges[lineIdx - 1][gearIdx + 1]?.let { factors.add(it) }
}
// check same line
if (gearIdx > 0) ranges[lineIdx][gearIdx - 1]?.let { factors.add(it) }
if (gearIdx < line.length) ranges[lineIdx][gearIdx + 1]?.let { factors.add(it) }
// check below line
if (lineIdx < input.size) {
if (gearIdx > 0) ranges[lineIdx + 1][gearIdx - 1]?.let { factors.add(it) }
if (ranges[lineIdx + 1][gearIdx - 1] != ranges[lineIdx + 1][gearIdx]) ranges[lineIdx + 1][gearIdx]?.let { factors.add(it) }
if (gearIdx < line.length && ranges[lineIdx + 1][gearIdx] != ranges[lineIdx + 1][gearIdx + 1]) ranges[lineIdx + 1][gearIdx + 1]?.let { factors.add(it) }
}
if (factors.size == 2) sum += factors[0] * factors[1]
gearIdx = line.indexOf('*', gearIdx + 1)
}
}
return sum
}
// Part 1 helper
private fun calcRanges(inputStr: String, offset: Int, lines: Int): Sequence<Pair<Int, List<Int>>> = "\\d+".toRegex().findAll(inputStr).map { match ->
var base = match.range.toList()
if (match.range.first % offset != 0) base = base.plus(match.range.first - 1)
if (match.range.last % offset != offset-1) base = base.plus(match.range.last + 1)
var valuesOfInterest = base.map { it - offset }.plus(base.map { it + offset })
if (match.range.first % offset != 0) valuesOfInterest = valuesOfInterest.plus(match.range.first - 1)
if (match.range.last % offset != offset-1) valuesOfInterest = valuesOfInterest.plus(match.range.last + 1)
valuesOfInterest = valuesOfInterest.filter { it >= 0 && it < offset * lines }
match.value.toInt() to valuesOfInterest
}
private fun isDigitOrDot(c: Char): Boolean = c.isDigit() || c == '.'
// Part 2 helper
}
| 0 | Kotlin | 0 | 0 | 7949d61d82d2b1a9b46cea386ae54d88b052606d | 3,139 | aoc23 | Apache License 2.0 |
src/Day16.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | /*
1. parse into Node(name: String, flow: Int, edgesOne: List<Edge>, edgesAll: List<Edge>)
where Edge(to: Node, hop: Int)
and edgesOne is the directly connected graph with hop=1 each time
2. derive edgesAll, all possible (N * N) - N connections with the hops in that edge
3. walk every possible non-cyclic path to visit all nodes accumulating a flow total
*/
fun main() {
val _day_ = 16
fun log(message: Any?) {
println(message)
}
data class Edge(val to: String, val hops: Int)
data class Node(val name:String, val flow: Int,
val edgeOne: List<Edge> = listOf(), val edgeAll: MutableList<Edge> = mutableListOf()
)
data class Graph(val g: List<Node>) {
val byName get() = g.associateBy { it.name }
val names get() = g.map { it.name }
}
// Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE
fun parse(input: List<String>): Graph {
val r = """Valve (..) has flow rate=(\d+); tunnels? leads? to valves? (.+)""".toRegex()
val graph: List<Node> = input.map { r.find(it)!!.destructured }.map { (name, flow, edges) ->
Node(name, flow.toInt(), edges.split(", ").map { Edge(it, 1) })
}
return Graph(graph)
}
fun shortestDistance(graph: Graph, from: String, to: String): Int {
val g = graph.byName
val frontier: MutableList<Pair<String, Int>> = mutableListOf(from to 0)
val visited: MutableSet<String> = mutableSetOf()
while (frontier.isNotEmpty()) {
val (name, hops) = frontier.removeAt(0)
if (name == to) { return hops }
if (name !in visited) {
visited.add(name)
g[name]?.edgeOne?.forEach { frontier.add(it.to to hops + 1) }
}
}
error("no route from $from to $to")
}
// for each node, find the shortest path to every other node (ie how many hops)
fun calculateAllRoutes(graph: Graph) {
graph.byName.values.forEach { v ->
val edges = graph.names.filter { it != v.name }.map { Edge(it, shortestDistance(graph, v.name, it)) }
v.edgeAll.addAll(edges)
}
}
// for the NxN routes, remove any destinations that have zero flow, no point checking those later
fun pruneZeroFlow(graph: Graph) {
val zeroFlowNodes = graph.g.filter { it.flow == 0 }.map { it.name }
graph.g.forEach { node ->
node.edgeAll.removeIf { it.to in zeroFlowNodes }
}
}
fun printGraph(graph: Graph) {
graph.g.forEachIndexed { i, v ->
log("$i -> Node(${v.name}, ${v.flow}, " +
"[${v.edgeOne.joinToString { it.to }}], ${v.edgeAll.size} -> [" +
"${v.edgeAll.joinToString { "${it.to}:${it.hops}" }}]")
}
}
fun longestDistance(graph: Any, name: String, it: String): Int {
return -1
}
fun calculateAllScores(graph: Graph) {
graph.byName.values.forEach { v ->
val edges = graph.names.filter { it != v.name }.map { Edge(it, longestDistance(graph, v.name, it)) }
v.edgeAll.addAll(edges)
}
}
fun part1(input: List<String>): Int {
val graph = parse(input)
calculateAllRoutes(graph)
pruneZeroFlow(graph)
printGraph(graph)
calculateAllScores(graph) // TODO: yeah hmm
return -1
}
fun part2(input: List<String>): Int {
return -2
}
// test inputs
val testInput = readInput("Day${_day_}_test.txt")
// test part 1
val test1 = part1(testInput)
check(test1 == 1651) { "!!! test part 1 failed with: $test1" }
// test part 2
val test2 = part2(testInput)
check(part2(testInput) == 222) { "!!! test part 2 failed with: $test2" }
// game inputs
val gameInput = readInput("Day${_day_}.txt")
// game part 1
val game1 = part1(gameInput)
println("*** game part 1: $game1")
check(game1 == 111111)
// game part 2
val game2 = part2(gameInput)
println("*** game part 2: $game2")
check(game2 == 222222)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 4,097 | aoc2022 | Apache License 2.0 |
src/Day12.kt | djleeds | 572,720,298 | false | {"Kotlin": 43505} | import java.util.*
data class Coordinates(val x: Int, val y: Int) {
val adjacent: List<Coordinates> by lazy {
listOf(Coordinates(x - 1, y), Coordinates(x + 1, y), Coordinates(x, y - 1), Coordinates(x, y + 1))
}
}
enum class PlotType {
START, END, OTHER;
companion object {
fun from(char: Char) = when (char) {
'S' -> START; 'E' -> END; else -> OTHER
}
}
}
data class Plot(val coordinates: Coordinates, val height: Int, val type: PlotType) {
companion object {
fun from(coordinates: Coordinates, char: Char) = Plot(
coordinates,
when (char) {
'S' -> 0; 'E' -> 'z' - 'a'; else -> char - 'a'
},
PlotType.from(char)
)
}
}
data class Step(val plot: Plot, val distance: Int = 0) {
infix fun toward(plot: Plot): Step = Step(plot, distance + 1)
}
class Terrain(private val plots: List<List<Plot>>) {
private val bounds = Bounds(plots.first().indices, plots.indices)
private val endPoint = findPlot { it.type == PlotType.END }
fun shortestDistance(isDestination: (Plot) -> Boolean): Int {
val visitedPlots = mutableSetOf(endPoint)
val steps: Queue<Step> = LinkedList<Step>().apply { add(Step(endPoint)) }
while (steps.isNotEmpty()) {
val step = steps.poll()
log { "Inspecting $step - Queue: $steps" }
if (isDestination(step.plot)) return step.distance
step.plot.coordinates.adjacent
.filter { it in bounds }
.map { plots[it] }
.filter { it.height >= step.plot.height - 1 }
.filter { it !in visitedPlots }
.forEach {
steps.add(step toward it)
visitedPlots.add(it)
}
}
throw IllegalStateException("Could not find a path that meets the criteria.")
}
private fun findPlot(predicate: (Plot) -> Boolean) = plots.flatten().first(predicate)
private operator fun <T> List<List<T>>.get(coordinates: Coordinates) = this[coordinates.y][coordinates.x]
private class Bounds(private val eastWestBounds: IntRange, private val northSouthBounds: IntRange) {
operator fun contains(coordinates: Coordinates) = coordinates.x in eastWestBounds && coordinates.y in northSouthBounds
}
companion object {
fun parse(input: List<String>) =
input.mapIndexed { y, row ->
row.mapIndexed { x, char ->
Plot.from(Coordinates(x, y), char)
}
}.let(::Terrain)
}
}
fun main() {
fun part1(input: List<String>): Int =
Terrain.parse(input).shortestDistance { it.type == PlotType.START }
fun part2(input: List<String>): Int =
Terrain.parse(input).shortestDistance { it.height == 0 }
val testInput = readInput("Day12_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 4 | 98946a517c5ab8cbb337439565f9eb35e0ce1c72 | 3,072 | advent-of-code-in-kotlin-2022 | Apache License 2.0 |
2021/src/day15/Day15.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day15
import readInput
import java.util.*
typealias Table = Array<Array<Point>>
data class Point(val value: Int, val minRisk: Int? = null)
data class Visit(val x: Int, val y: Int, val currentRisk: Int)
fun List<String>.toMultipliedTable(multiplyBy: Int = 5): Table {
val table = Array(size * multiplyBy) { arrayOf<Point>() }
for (i in 0 until size * multiplyBy) {
val row = mutableListOf<Point>()
val downMultiplier = i / size
repeat(multiplyBy) { repeat ->
row.addAll(this[i % size].chunked(1).map {
val newNumber = (it.toInt() + repeat + downMultiplier)
Point(if (newNumber > 9) newNumber % 9 else newNumber)
}.toTypedArray())
}
table[i] = row.toTypedArray()
}
return table
}
fun Table.getValueOrNull(x: Int, y: Int) = if (x < 0 || y < 0 || y >= size || x >= this[y].size) null else this[y][x].value
fun runDijkstra(table: Table) : Int {
val toVisits: PriorityQueue<Visit> = PriorityQueue<Visit> { a, b ->
a.currentRisk - b.currentRisk
}.also { it.add(Visit(0, 0 ,0)) } // start on the top left, with 0 risk
while (toVisits.isNotEmpty()) {
val curr = toVisits.remove()
val x = curr.x
val y = curr.y
val cumulatedRisk = curr.currentRisk + table[y][x].value
val currMinRisk = table[y][x].minRisk
// We have visited this path and have already a risk lower than the current exploration
if (currMinRisk != null && currMinRisk <= cumulatedRisk) {
continue
}
table[y][x] = table[y][x].copy(minRisk = cumulatedRisk) // update the smallest risk for the cell
if (y == table.size - 1 && x == table[y].size - 1) { // destination reached
println("found final destination ($x, $y) = $cumulatedRisk")
break
} else {
mapOf(
Visit(x + 1, y, cumulatedRisk) to table.getValueOrNull(x + 1, y), // right
Visit(x, y + 1, cumulatedRisk) to table.getValueOrNull(x, y + 1), // bottom
Visit(x - 1, y, cumulatedRisk) to table.getValueOrNull(x - 1, y), // left
Visit(x, y - 1, cumulatedRisk) to table.getValueOrNull(x,y - 1), // top
).filterValues { it != null } // remove OOB values
.forEach {
toVisits.add(it.key) // add the next paths to visit in an ordered stack
}
}
}
return table.last().last().minRisk?.let { it - table.first().first().value } ?: -1
}
fun part1(lines: List<String>) = runDijkstra(lines.toMultipliedTable(1))
fun part2(lines: List<String>) = runDijkstra(lines.toMultipliedTable(5))
fun main() {
val testInput = readInput("day15/test")
println("part1(testInput) => " + part1(testInput)) // 40
println("part2(testInput) => " + part2(testInput)) // 315
val input = readInput("day15/input")
println("part1(input) => " + part1(input)) // 717
println("part2(input) => " + part2(input)) // 2993
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 3,047 | advent-of-code | Apache License 2.0 |
src/day10/Day10.kt | bartoszm | 572,719,007 | false | {"Kotlin": 39186} | package day10
import readInput
import toPair
fun main() {
val testInput = parse(readInput("day10/test"))
val input = parse(readInput("day10/input"))
println("${solve1(testInput)} ${solve1gen(testInput)}")
println("${solve1(input)} ${solve1gen(input)}")
solve2(testInput).forEach { println(it) }
println("-----")
solve2(input).forEach { println(it) }
println("-----")
solve2gen(input).forEach { println(it) }
}
fun execute(v: Int, cycle: Int, cmd: Cmd): Sequence<Pair<Int, Int>> {
return when(cmd){
Noop -> sequenceOf(v to cycle + 1)
is AddX -> sequenceOf(v to cycle + 1, v + cmd.value to cycle + 2)
}
}
fun solve1gen(input: List<Cmd>): Int {
return process(1 to 1, input)
.filter { (_, c) -> (c - 20) % 40 == 0 }
.takeWhile { (_,c) -> c <= 220 }
.sumOf { (v,c) -> v * c }
}
fun solve2gen(input: List<Cmd>): List<String> {
val size = 40
return process(0 to 0, input)
.map {(value, cycle) -> if (cycle % size in value..value + 2) '#' else '.' }
.chunked(size)
.map { c -> c.joinToString("") }.toList()
}
fun process(init: Pair<Int,Int>, cmds: List<Cmd>): Sequence<Pair<Int, Int>> {
val iter = cmds.iterator()
return generateSequence(seed = sequenceOf(init)) { last ->
val (v,c) = last.last()
if(iter.hasNext()) execute(v,c, iter.next()) else null
}.flatMap { it }
}
fun solve1(input: List<Cmd>): Int {
var cycle = 1
var value = 1
var emmit = 20
val emmits = sequence {
for (cmd in input) {
for ((v, c) in execute(value, cycle, cmd)) {
if (cycle == emmit) {
yield(value to cycle)
emmit += 40
}
cycle = c
value = v
}
}
}
return emmits.takeWhile{ it.second <= 220}.map{(v,c) -> v * c}.sum()
}
fun solve2(input: List<Cmd>): List<String> {
var cycle = 0
var value = 0
val size = 40
return sequence {
for (cmd in input) {
for ((v, c) in execute(value, cycle, cmd)) {
yield(if (cycle % size in value..value + 2) '#' else '.')
cycle = c
value = v
}
}
}.chunked(size).map { c -> c.joinToString("") }.toList()
}
sealed class Cmd(val cycles: Int)
object Noop : Cmd(1)
class AddX(val value: Int) : Cmd(2)
fun parse(input: List<String>): List<Cmd> {
fun read(s:String): Cmd {
val (_, v) = s.split("""\s+""".toRegex()).toPair()
return AddX(v.toInt())
}
return input.map {
if(it == "noop") Noop
else read(it)
}
}
| 0 | Kotlin | 0 | 0 | f1ac6838de23beb71a5636976d6c157a5be344ac | 2,695 | aoc-2022 | Apache License 2.0 |
src/Day15.kt | eo | 574,058,285 | false | {"Kotlin": 45178} | import kotlin.math.abs
// https://adventofcode.com/2022/day/15
fun main() {
fun parseInput(input: List<String>): List<SensorBeaconPair> {
val regex = "x=(-?\\d+), y=(-?\\d+)".toRegex()
return input
.flatMap { regex.findAll(it) }
.map { Coordinate(it.groupValues[1].toInt(), it.groupValues[2].toInt()) }
.chunked(2)
.map { (first, second) -> SensorBeaconPair(first, second) }
}
fun List<IntRange>.merged(): List<IntRange> {
if (isEmpty()) return this
val sortedRanges = sortedBy(IntRange::first)
val mergedRanges = mutableListOf(sortedRanges.first())
(1..sortedRanges.lastIndex).forEach { index ->
if (mergedRanges.last().last + 1 < sortedRanges[index].first) {
mergedRanges += sortedRanges[index]
} else if (mergedRanges.last().last < sortedRanges[index].last) {
mergedRanges[mergedRanges.lastIndex] =
mergedRanges.last().first..sortedRanges[index].last
}
}
return mergedRanges
}
fun List<IntRange>.countValuesContained(values: Collection<Int>): Int {
val sortedValues = ArrayDeque(values.sorted())
var count = 0
for (range in this) {
while (
sortedValues.isNotEmpty() &&
sortedValues.first() < range.first
) {
sortedValues.removeFirst()
}
while (
sortedValues.isNotEmpty() &&
sortedValues.first() <= range.last
) {
sortedValues.removeFirst()
count++
}
if (sortedValues.isEmpty()) {
break
}
}
return count
}
fun IntRange.findMissing(ranges: List<IntRange>): Int? {
val firstRange = ranges.first()
return if (firstRange.first <= first && firstRange.last >= last) {
return null
} else if (firstRange.first == first + 1) {
first
} else if (firstRange.last == last - 1) {
last
} else if (ranges.size == 2 && firstRange.last + 1 == ranges[1].first - 1) {
firstRange.last + 1
} else {
error("More than 1 missing value means multiple solutions!")
}
}
fun part1(input: List<String>): Int {
val rowOfInterest = 10
val sensorBeaconPairs = parseInput(input)
val noBeaconRanges = sensorBeaconPairs
.mapNotNull { it.noBeaconRangeAtY(rowOfInterest) }
.merged()
val xCoordinatesOfBeaconsAtY = sensorBeaconPairs
.map(SensorBeaconPair::beaconCoordinate)
.filter { it.y == rowOfInterest }
.map(Coordinate::x)
.distinct()
val totalSizeOfNoBeaconRanges = noBeaconRanges.sumOf { it.last - it.first + 1 }
val numberOfBeaconsInNoBeaconRanges =
noBeaconRanges.countValuesContained(xCoordinatesOfBeaconsAtY)
return totalSizeOfNoBeaconRanges - numberOfBeaconsInNoBeaconRanges
}
fun part2(input: List<String>): Long {
val maxSize = 20
val tuningFreqMultiplier = 4_000_000L
val rangeOfInterest = 0..maxSize
val sensorBeaconPairs = parseInput(input)
for (y in rangeOfInterest) {
val noBeaconRanges = sensorBeaconPairs
.mapNotNull { it.noBeaconRangeAtY(y) }
.filterNot { it.last < 0 || it.first > maxSize }
.merged()
.map { if (it.first < 0) 0..it.last else it }
.map { if (it.last > maxSize) it.first..maxSize else it }
rangeOfInterest.findMissing(noBeaconRanges)?.let {
return it * tuningFreqMultiplier + y
}
}
return 0
}
val input = readLines("Input15")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
private data class Coordinate(val x: Int, val y: Int) {
fun distanceTo(other: Coordinate) = abs(x - other.x) + abs(y - other.y)
}
private class SensorBeaconPair(val sensorCoordinate: Coordinate, val beaconCoordinate: Coordinate) {
val distanceInBetween = sensorCoordinate.distanceTo(beaconCoordinate)
fun noBeaconRangeAtY(y: Int): IntRange? {
val verticalDistance = abs(sensorCoordinate.y - y)
val horizontalDistance = distanceInBetween - verticalDistance
return if (horizontalDistance >= 0) {
(sensorCoordinate.x - horizontalDistance)..(sensorCoordinate.x + horizontalDistance)
} else {
null
}
}
} | 0 | Kotlin | 0 | 0 | 8661e4c380b45c19e6ecd590d657c9c396f72a05 | 4,685 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day08.kt | leeturner | 572,659,397 | false | {"Kotlin": 13839} | typealias Grid = List<List<Int>>
data class Coordinate(val row: Int, val col: Int)
fun List<String>.parseGrid(): Grid {
return this.map { line -> line.map { tree -> tree.digitToInt() } }
}
fun Grid.isEdge(coordinate: Coordinate): Boolean {
return coordinate.row == 0 ||
coordinate.row == this.size - 1 ||
coordinate.col == 0 ||
coordinate.col == this.first().size - 1
}
fun Grid.visibleOnRow(coordinate: Coordinate): Boolean {
val tree = this[coordinate.row][coordinate.col]
return this[coordinate.row].subList(0, coordinate.col).max() < tree ||
this[coordinate.row].subList(coordinate.col + 1, this[coordinate.row].size).max() < tree
}
fun Grid.visibleOnColumn(coordinate: Coordinate): Boolean {
val tree = this[coordinate.row][coordinate.col]
val column = this.map { it[coordinate.col] }
return column.subList(0, coordinate.row).max() < tree ||
column.subList(coordinate.row + 1, column.size).max() < tree
}
fun Grid.visibleTrees(): List<Int> {
val visible = mutableListOf<Int>()
this.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, col ->
if (isEdge(Coordinate(rowIndex, colIndex))) {
visible.add(col)
} else if (visibleOnRow(Coordinate(rowIndex, colIndex))) {
visible.add(col)
} else if (visibleOnColumn(Coordinate(rowIndex, colIndex))) visible.add(col)
}
}
return visible
}
fun Grid.calculateScore(coordinate: Coordinate): Int {
val tree = this[coordinate.row][coordinate.col]
val column = this.map { it[coordinate.col] }
// look left
val leftSection = this[coordinate.row].subList(0, coordinate.col)
val left =
if (leftSection.indexOfLast { it >= tree } != -1)
leftSection.size - leftSection.indexOfLast { it >= tree }
else leftSection.size
// look right
val rightSection = this[coordinate.row].subList(coordinate.col + 1, this[coordinate.row].size)
val right =
if (rightSection.indexOfFirst { it >= tree } != -1)
rightSection.indexOfFirst { it >= tree } + 1
else rightSection.size
// look up
val upSection = column.subList(0, coordinate.row)
val up =
if (upSection.indexOfLast { it >= tree } != -1)
coordinate.row - upSection.indexOfLast { it >= tree }
else upSection.size
// look down
val downSection = column.subList(coordinate.row + 1, column.size)
val down =
if (downSection.indexOfFirst { it >= tree } != -1) downSection.indexOfFirst { it >= tree } + 1
else downSection.size
return left * right * up * down
}
fun Grid.scenicScores(): List<Int> {
val scores = mutableListOf<Int>()
this.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, col ->
scores.add(calculateScore(Coordinate(rowIndex, colIndex)))
}
}
return scores
}
fun main() {
fun part1(input: List<String>): Int {
return input.parseGrid().visibleTrees().size
}
fun part2(input: List<String>): Int {
return input.parseGrid().scenicScores().max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input)) // 1801
println(part2(input)) // 209880
}
| 0 | Kotlin | 0 | 0 | 8da94b6a0de98c984b2302b2565e696257fbb464 | 3,284 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | Shykial | 572,927,053 | false | {"Kotlin": 29698} | fun main() {
fun part1(input: List<String>): Int {
val mapped = input.mapInner(Char::digitToInt)
return mapped.borderSize + mapped
.subList(1, input.lastIndex)
.sumOfIndexed { lineIndex, line ->
line.subList(1, line.lastIndex).countIndexed { digitIndex, d ->
d > minOf(
line.subList(digitIndex + 2, line.size).max(),
line.subList(0, digitIndex + 1).max(),
mapped.subList(0, lineIndex + 1).maxOf { it[digitIndex + 1] },
mapped.subList(lineIndex + 2, mapped.size).maxOf { it[digitIndex + 1] }
)
}
}
}
fun part2(input: List<String>): Int {
val mapped = input.mapInner(Char::digitToInt)
return mapped
.subList(1, input.lastIndex)
.flatMapIndexed { lineIndex, line ->
line.subList(1, line.lastIndex).mapIndexed { digitIndex: Int, d: Int ->
productOf(
line.subList(digitIndex + 2, line.size).viewingDistanceFrom(d),
line.subList(0, digitIndex + 1).asReversed().viewingDistanceFrom(d),
mapped.subList(0, lineIndex + 1).asReversed().map { it[digitIndex + 1] }.viewingDistanceFrom(d),
mapped.subList(lineIndex + 2, mapped.size).map { it[digitIndex + 1] }.viewingDistanceFrom(d)
)
}
}.max()
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
private val <T> Collection<Collection<T>>.borderSize: Int
get() = first().size * 2 + 2 * (size - 2)
private fun List<Int>.viewingDistanceFrom(digit: Int) =
1 + (indexOfFirst { it >= digit }.takeIf { it != -1 } ?: lastIndex)
| 0 | Kotlin | 0 | 0 | afa053c1753a58e2437f3fb019ad3532cb83b92e | 1,865 | advent-of-code-2022 | Apache License 2.0 |
src/day07/Day07.kt | martinhrvn | 724,678,473 | false | {"Kotlin": 27307, "Jupyter Notebook": 1336} | package day07
import AdventDay
import readInput
enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND
}
data class Hand(val cards: List<String>, val bet: Long) {
fun getCardValue(card: String, isJoker: Boolean = false): Long {
return when (card) {
"A" -> 14
"K" -> 13
"Q" -> 12
"J" -> if (isJoker) 1 else 11
"T" -> 10
else -> card.toLong()
}
}
private fun groupCards() =
cards
.groupBy { it }
.mapValues { (_, cards) -> cards.size }
.entries
.sortedByDescending { it.value }
private fun evaluateCardCounts(counts: List<Int>): HandType =
when (counts) {
listOf(5) -> HandType.FIVE_OF_A_KIND
listOf(4, 1) -> HandType.FOUR_OF_A_KIND
listOf(3, 2) -> HandType.FULL_HOUSE
listOf(3, 1, 1) -> HandType.THREE_OF_A_KIND
listOf(2, 2, 1) -> HandType.TWO_PAIR
listOf(2, 1, 1, 1) -> HandType.ONE_PAIR
else -> HandType.HIGH_CARD
}
private fun evaluateHand(): HandType {
val counts = groupCards().map { it.value }
return evaluateCardCounts(counts)
}
private fun evaluateHandWithJokers(): HandType {
val cardCounts = groupCards()
val jokerCount = cards.count { it == "J" }
val maxCount = cardCounts.filter { it.key != "J" }.map { it.value }.ifEmpty { listOf(0) }
val counts = listOf(maxCount.first() + jokerCount) + maxCount.drop(1)
return evaluateCardCounts(counts)
}
fun compareTo(other: Hand, hasJokers: Boolean): Int {
val handType1 = if (hasJokers) evaluateHandWithJokers() else evaluateHand()
val handType2 = if (hasJokers) other.evaluateHandWithJokers() else other.evaluateHand()
if (handType1 != handType2) {
return handType1.compareTo(handType2)
}
cards.zip(other.cards).forEach { (card1, card2) ->
val cardValue1 = getCardValue(card1, hasJokers)
val cardValue2 = getCardValue(card2, hasJokers)
if (cardValue1 != cardValue2) {
return cardValue1.compareTo(cardValue2)
}
}
return 0
}
companion object {
fun parseHand(input: String): Hand {
val (cards, bet) = input.split(" ")
return Hand(cards.split("").filter { it.isNotEmpty() }, bet.toLong())
}
}
}
class Day07(val input: List<String>) : AdventDay {
fun calculateScore(hasJokers: Boolean): Long =
input
.map { Hand.parseHand(it) }
.sortedWith { h1, h2 -> h1.compareTo(h2, hasJokers) }
.mapIndexed { i, v -> (i + 1) * v.bet }
.sum()
override fun part1(): Long {
return calculateScore(hasJokers = false)
}
override fun part2(): Long {
return calculateScore(hasJokers = true)
}
}
fun main() {
val day07 = Day07(readInput("day07/Day07"))
println(day07.part1())
println(day07.part2())
}
| 0 | Kotlin | 0 | 0 | 59119fba430700e7e2f8379a7f8ecd3d6a975ab8 | 2,883 | advent-of-code-2023-kotlin | Apache License 2.0 |
src/year2023/day19/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2023.day19
import arrow.core.nonEmptyListOf
import utils.ProblemPart
import utils.readInputs
import utils.runAlgorithm
import utils.size
fun main() {
val (realInput, testInputs) = readInputs(2023, 19, transform = ::parse)
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(19114),
algorithm = { (parts, workflow) -> part1(parts, workflow) },
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(167409079868000),
algorithm = { (_, workflow) -> part2(workflow) },
),
)
}
private fun parse(input: List<String>): Pair<List<Map<String, Long>>, Map<String, List<Rule>>> {
val workflow = input.asSequence()
.takeWhile { it.isNotBlank() }
.mapNotNull(parseWorkflowRegex::matchEntire)
.map { it.groupValues }
.associate { (_, nodeIdentifier, rules) ->
nodeIdentifier to parseConditionRegex.findAll(rules)
.map { it.groupValues }
.map { (_, attribute, operation, threshold, destinationIdentifier) ->
Rule(
attribute = attribute,
isGreaterThan = operation == ">",
threshold = threshold.toLongOrNull(),
destinationIdentifier = destinationIdentifier,
)
}
.toList()
}
val parts = input.takeLastWhile { it.isNotBlank() }
.map { line ->
parsePartRegex.findAll(line).associate { match ->
match.groupValues[1] to match.groupValues[2].toLong()
}
}
return parts to workflow
}
private val parseWorkflowRegex = "(.+?)\\{(.+)\\}".toRegex()
private val parseConditionRegex = "(?:([xmas])([<>])(\\d+):)?([^,]+)".toRegex()
private val parsePartRegex = "([xmas])=(\\d+)".toRegex()
private fun part1(parts: List<Map<String, Long>>, workflow: Map<String, List<Rule>>): Long {
val rules = workflow.mapValues { (_, rules) ->
rules.asSequence()
.map { rule ->
if (rule.threshold == null) {
{ _: Map<String, Long> -> rule.destinationIdentifier }
} else {
val matchesCondition: (Long) -> Boolean = if (rule.isGreaterThan) {
{ it > rule.threshold }
} else {
{ it < rule.threshold }
}
{ part: Map<String, Long> ->
if (matchesCondition(part.getValue(rule.attribute))) rule.destinationIdentifier
else null
}
}
}
.reduce { ruleA, ruleB ->
{ part ->
ruleA(part) ?: ruleB(part)
}
}
.let { findDestination ->
{ part: Map<String, Long> -> findDestination(part)!! }
}
}
return parts.asSequence()
.filter { part ->
generateSequence("in") { ruleKey -> rules.getValue(ruleKey)(part) }
.first { it in setOf("R", "A") } == "A"
}
.sumOf { acceptedPart ->
acceptedPart.asSequence().sumOf { it.value }
}
}
private fun part2(rules: Map<String, List<Rule>>): Long {
return generateSequence(
listOf(
"in" to mapOf("x" to 1L..4000L, "m" to 1L..4000L, "a" to 1L..4000L, "s" to 1L..4000L)
)
) { states ->
states.asSequence()
.filterNot { (nodeKey) -> nodeKey in setOf("R", "A") }
.flatMap { initialState ->
rules.getValue(initialState.first).fold(mutableListOf(initialState)) { states, rule ->
states.apply {
addAll(removeLast().second.apply(rule))
}
}
}
.toList()
.takeUnless { it.isEmpty() }
}
.flatten()
.filter { it.first == "A" }
.map { it.second }
.sumOf { acceptedPart ->
acceptedPart.asSequence()
.map { it.value.size }
.reduce(Long::times)
}
}
private fun Map<String, LongRange>.apply(rule: Rule): Sequence<Pair<String, Map<String, LongRange>>> {
return if (rule.threshold == null) sequenceOf(rule.destinationIdentifier to this)
else getValue(rule.attribute)
.let { initialRange ->
if (rule.isGreaterThan) sequenceOf(
(rule.threshold + 1)..initialRange.last,
initialRange.first..rule.threshold,
) else sequenceOf(
initialRange.first..<rule.threshold,
rule.threshold..initialRange.last,
)
}
.map { toMutableMap().apply { this[rule.attribute] = it } }
.map { rule.destinationIdentifier to it }
}
private data class Rule(
val attribute: String,
val isGreaterThan: Boolean,
val threshold: Long?,
val destinationIdentifier: String,
)
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 5,157 | Advent-of-Code | Apache License 2.0 |
src/Day02.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} |
enum class Play(val first: Char, val part1Second: Char) {
Rock('A','X'),
Paper('B','Y'),
Scissors('C','Z'); // More plays can be added, in order
val score = ordinal+1
val winner get() = values()[(ordinal + 1) % values().size]
val loser get() = values()[(ordinal - 1 + values().size) % values().size]
}
fun Char.toPlay(responseCode: Boolean=false) =
Play.values().first { this == if (responseCode) it.part1Second else it.first }
enum class RoundResult(val score:Int, val part2Symbol: Char, val toResponse: (opponent: Play) -> Play) {
Win(6,'Z', { it.winner } ),
Draw(3,'Y', { it } ),
Lose(0,'X', { it.loser })
}
fun Char.toResult() = RoundResult.values().first { this == it.part2Symbol }
data class Round(val opponent: Play, val response: Play) {
private fun toResult() = RoundResult.values().first { response == it.toResponse(opponent) }
fun toScore() = response.score + toResult().score
}
fun String.toRound( response: (symbol: Char, opponent: Play) -> Play ): Round {
require(length == 3 && this[1] == ' ')
val opponent = this[0].toPlay()
return Round(opponent, response(this[2], opponent))
}
private fun part1(lines: List<String>): Int =
lines.sumOf { it.toRound { symbol, _ -> symbol.toPlay(responseCode = true) }.toScore() }
private fun part2(lines: List<String>): Int =
lines.sumOf { it.toRound { symbol, opponent -> symbol.toResult().toResponse(opponent) }.toScore() }
fun main() {
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input)) // 14375
println(part2(input)) // 10274
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 1,688 | aoc2022 | Apache License 2.0 |
2023/src/main/kotlin/day7.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parse
import utils.Parser
import utils.Solution
import utils.mapItems
import utils.pow
import utils.withCounts
fun main() {
Day7.run()
}
object Day7 : Solution<List<Day7.Hand>>() {
override val name = "day7"
override val parser = Parser.lines.mapItems { parseHand(it) }
@Parse("{cards} {bid}")
data class Hand(
val cards: String,
val bid: Long,
) {
fun rank(wildcards: Boolean): Long {
val counts = cardCounts(wildcards)
val rank = when (counts) {
listOf(5) -> 8L
listOf(4, 1) -> 7L
listOf(3, 2) -> 6L
listOf(3, 1, 1) -> 5L
listOf(2, 2, 1) -> 4L
listOf(2, 1, 1, 1) -> 3L
else -> 2
}
val chars = if (wildcards) "J23456789TQKA" else "23456789TJQKA"
val strength = cards.toCharArray().mapIndexed { index, char -> chars.indexOf(char) * 100L.pow(4 - index) }.reduce { a, b -> a + b }
return rank * 100L.pow(5) + strength
}
private fun cardCounts(wildcards: Boolean): List<Int> {
val counts = cards.toCharArray().toList().withCounts()
return if (!wildcards) {
counts.values.sortedDescending()
} else {
val wildcardCount = counts['J'] ?: 0
val noWildcards = counts
.filter { (k, _) -> k != 'J' }.values
.sortedDescending().takeIf { it.isNotEmpty() } ?: listOf(0)
listOf((noWildcards.first() + wildcardCount).coerceAtMost(5)) + noWildcards.drop(1)
}
}
}
override fun part1(input: List<Hand>): Long {
val ranked = input.sortedBy { it.rank(wildcards = false) }
return ranked.withIndex().sumOf { (i, hand) -> (i + 1) * hand.bid }
}
override fun part2(input: List<Hand>): Long {
val ranked = input.sortedBy { it.rank(wildcards = true) }
return ranked.withIndex().sumOf { (i, hand) -> (i + 1) * hand.bid }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,847 | aoc_kotlin | MIT License |
src/Day16b.kt | michaelYuenAE | 573,094,416 | false | {"Kotlin": 74685} | import kotlin.math.abs
import kotlin.math.max
fun main() {
println(Day16b().solve2().toString())
}
class Day16b() {
private val parsed = readInput("day16_input").map { Valve.from(it) }
private val valves = parsed.associateBy { it.id }
private val shortestPaths =
floydWarshall(parsed.associate { it.id to it.neighborIds.associateWith { 1 }.toMutableMap() }.toMutableMap())
private var score = 0
private var totalTime = 30
fun solve1(): Int {
dfs(0, "AA", emptySet(), 0)
return score
}
fun solve2(): Int {
totalTime = 26
score = 0
dfs(0, "AA", emptySet(), 0, true)
return score
}
private fun dfs(currScore: Int, currentValve: String, visited: Set<String>, time: Int, part2: Boolean = false) {
score = max(score, currScore)
for ((valve, dist) in shortestPaths[currentValve]!!) {
if (!visited.contains(valve) && time + dist + 1 < totalTime) {
dfs(
currScore + (totalTime - time - dist - 1) * valves[valve]?.flowRate!!,
valve,
visited.union(listOf(valve)),
time + dist + 1,
part2
)
}
}
if(part2)
dfs(currScore, "AA", visited, 0, false)
}
private fun floydWarshall(shortestPaths: MutableMap<String, MutableMap<String, Int>>): MutableMap<String, MutableMap<String, Int>> {
for (k in shortestPaths.keys) {
for (i in shortestPaths.keys) {
for (j in shortestPaths.keys) {
val ik = shortestPaths[i]?.get(k) ?: 9999
val kj = shortestPaths[k]?.get(j) ?: 9999
val ij = shortestPaths[i]?.get(j) ?: 9999
if (ik + kj < ij)
shortestPaths[i]?.set(j, ik + kj)
}
}
}
//remove all paths that lead to a valve with rate 0
shortestPaths.values.forEach {
it.keys.map { key -> if (valves[key]?.flowRate == 0) key else "" }
.forEach { toRemove -> if (toRemove != "") it.remove(toRemove) }
}
//remove all paths that lead back to the starting room
shortestPaths.values.forEach { it.remove("AA") }
return shortestPaths
}
data class Valve(val id: String, val flowRate: Int, val neighborIds: List<String>) {
companion object {
fun from(line: String): Valve {
val (name, rate) = line.split("; ")[0].split(" ").let { it[1] to it[4].split("=")[1].toInt() }
val neighbors = line.split(", ").toMutableList()
neighbors[0] = neighbors[0].takeLast(2)
return Valve(name, rate, neighbors)
}
}
}
} | 0 | Kotlin | 0 | 0 | ee521263dee60dd3462bea9302476c456bfebdf8 | 2,844 | advent22 | Apache License 2.0 |
2022/src/day08/day08.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day08
import GREEN
import RESET
import printTimeMillis
import readInput
import kotlin.math.max
fun isTreeVisible(input: List<String>, posY: Int, posX: Int) : Boolean {
val left = input[posY].take(posX).reversed().all { it < input[posY][posX] }
val right = input[posY].drop(posX + 1).all { it < input[posY][posX] }
val top = input.take(posY).map { it[posX] }.joinToString("").reversed().all { it < input[posY][posX] }
val bottom = input.drop(posY + 1).map { it[posX] }.joinToString("").all { it < input[posY][posX] }
return left || right || top || bottom
}
fun part1(input: List<String>): Int {
var sum = 0
for (y in input.indices) {
for (x in 0 until input[y].length) {
if (isTreeVisible(input, y, x)) {
sum += 1
}
}
}
return sum
}
fun calculateScenicScore(input: List<String>, posY: Int, posX: Int): Int {
val left = input[posY].take(posX).reversed()
val leftScore = left.takeWhile { it < input[posY][posX] }.let {
if (left.length > it.length) { it.length + 1 }
else { it.length }
}
val right = input[posY].drop(posX + 1)
val rightScore = right.takeWhile { it < input[posY][posX] }.let {
if (right.length > it.length) { it.length + 1 }
else { it.length }
}
val top = input.take(posY).map { it[posX] }.joinToString("").reversed()
val topScore = top.takeWhile { it < input[posY][posX] }.let {
if (top.length > it.length) { it.length + 1 }
else { it.length }
}
val bottom = input.drop(posY + 1).map { it[posX] }.joinToString("")
val bottomScore = bottom.takeWhile { it < input[posY][posX] }.let {
if (bottom.length > it.length) { it.length + 1 }
else { it.length }
}
return leftScore * rightScore * topScore * bottomScore
}
fun part2(input: List<String>): Int {
var maxScenicScore = 0
for (y in input.indices) {
for (x in 0 until input[y].length) {
maxScenicScore = max(maxScenicScore, calculateScenicScore(input, y, x))
}
}
return maxScenicScore
}
fun main() {
val testInput = readInput("day08_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day08.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 2,543 | advent-of-code | Apache License 2.0 |
aoc/src/main/kotlin/com/bloidonia/aoc2023/day07/Main.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.day07
import com.bloidonia.aoc2023.lines
import java.lang.Math.pow
private const val example = """32T3K 765
T55J5 684
KK677 28
KTJJT 220
QQQJA 483"""
private val part1CardOrder = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A")
private val part2CardOrder = listOf("J", "1", "2", "3", "4", "5", "6", "7", "8", "9", "T", "Q", "K", "A")
private data class Hand(val cards: Cards, val bet: Long) {
constructor(line: String, part1: Boolean) : this(
Cards(line.split(Regex("\\s+"))[0].toList().map { "$it" }, part1),
line.split(Regex("\\s+"))[1].toLong(),
)
}
private data class Cards(
val cards: List<String>,
val part1: Boolean,
val rank: Int = (if (part1) cards else cards.filter { it != "J" }).groupBy { it }.values.map { it.size }.sortedDescending().let { counts ->
val jokers = if (part1) 0 else cards.count { it == "J" }
when {
jokers == 5 || counts[0] + jokers == 5 -> 7 // Five of a kind
counts[0] + jokers == 4 -> 6 // Four of a kind
counts[0] + jokers == 3 && counts[1] == 2 -> 5 // Full house
counts[0] + jokers == 3 -> 4 // Three of a kind
counts[0] == 2 && counts[1] == 2 -> 3 // Two pair -- can't be got with Jokers
counts[0] + jokers == 2 -> 2 // One pair
else -> 1 // High card
}
},
// Score is a base 14 number
val score: Double = cards.reversed().mapIndexed { index, card ->
if (part1)
part1CardOrder.indexOf(card) * pow(part1CardOrder.size.toDouble(), index.toDouble())
else
part2CardOrder.indexOf(card) * pow(part2CardOrder.size.toDouble(), index.toDouble())
}.sum()
)
private fun handComparator(a: Hand, b: Hand) = a.cards.rank.compareTo(b.cards.rank).let { if (it != 0) it else a.cards.score.compareTo(b.cards.score) }
private fun score(hands: List<Hand>) = hands.sortedWith(::handComparator)
.mapIndexed { idx, g -> (idx + 1) * g.bet }
.sum()
private fun part1(input: List<String>) = score(input.map { Hand(it, true) })
private fun part2(input: List<String>) = score(input.map { Hand(it, false) })
fun main() {
println("Example: ${part1(example.lines())}")
println("Part 1: ${part1(lines("/day07.input"))}")
println("Example: ${part2(example.lines())}")
println("Part 2: ${part2(lines("/day07.input"))}")
} | 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 2,414 | aoc-2023 | MIT License |
src/Day02.kt | martintomac | 726,272,603 | false | {"Kotlin": 19489} | import Game.ColorCubes
private val colors = setOf("red", "green", "blue")
private val lineFormat = "Game (\\d+): (.+)".toRegex()
private fun parseGame(line: String): Game {
fun String.extractNumAndColor(): ColorCubes {
val (numStr, color) = split(" ")
return ColorCubes(numStr.toInt(), color)
}
fun String.parseAsDrawSetup() =
split(",")
.map { it.trim() }
.map { it.extractNumAndColor() }
fun String.parseGameSetups() =
split(";")
.map { it.trim() }
.map { it.parseAsDrawSetup() }
val (gameIdStr, gameSetup) = lineFormat.matchEntire(line)!!.destructured
return Game(gameIdStr.toInt(), gameSetup.parseGameSetups())
}
data class Game(
val id: Int,
val draws: List<List<ColorCubes>>
) {
data class ColorCubes(
val count: Int,
val color: String,
)
}
fun sumLegalGameIds(lines: List<String>): Int {
fun getMaxAllowedNumOfCubes(color: String) =
when (color) {
"red" -> 12
"green" -> 13
"blue" -> 14
else -> 0
}
fun Game.isIllegal() = draws.any { colorCubes ->
colorCubes.any { it.count > getMaxAllowedNumOfCubes(it.color) }
}
fun Game.isLegal() = !isIllegal()
fun sumLegalGameIds(games: List<Game>) =
games.filterNot { it.isLegal() }
.sumOf { it.id }
val games = lines.map { parseGame(it) }
return sumLegalGameIds(games)
}
fun sumOfGamePowers(lines: List<String>): Int {
fun Game.maxCountOfColorOrNull(color: String) =
draws.flatten()
.filter { it.color == color }
.maxOfOrNull { it.count }
val games = lines.map { parseGame(it) }
return games.sumOf { game ->
colors.mapNotNull { color -> game.maxCountOfColorOrNull(color) }
.reduce { power, count -> power * count }
}
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
sumLegalGameIds(testInput).println()
sumOfGamePowers(testInput).println()
val input = readInput("Day02")
sumLegalGameIds(input).println()
sumOfGamePowers(input).println()
}
| 0 | Kotlin | 0 | 0 | dc97b23f8461ceb9eb5a53d33986fb1e26469964 | 2,233 | advent-of-code-2023 | Apache License 2.0 |
Subsets and Splits