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/Day12.kt
|
punx120
| 573,421,386 | false |
{"Kotlin": 30825}
|
fun main() {
fun buildMap(input: List<String>): Array<CharArray> {
val n = input[0].length
val map = Array(n) { CharArray(n) }
for (r in input.indices) {
for (c in input[r].indices)
map[r][c] = input[r][c]
}
return map
}
fun findStartAndEnd(map: Array<CharArray>): Pair<Pair<Int, Int>, Pair<Int, Int>> {
var end: Pair<Int, Int>? = null
var start: Pair<Int, Int>? = null
val n = map.size
// find E
for (r in 0 until n) {
for (c in 0 until n) {
if (map[r][c] == 'E') {
end = Pair(r, c)
if (start != null) {
return Pair(start, end)
}
} else if (map[r][c] == 'S') {
start = Pair(r, c)
if (end != null) {
return Pair(start, end)
}
}
}
}
throw RuntimeException("Invalid input")
}
fun part1(map: Array<CharArray>, multipleStart : Boolean): Int {
val n = map.size
val visited = Array(n) { IntArray(n) { -1 } }
val to_visit = mutableSetOf<Pair<Int, Int>>()
val (start, end) = findStartAndEnd(map)
map[end.first][end.second] = 'z'
map[start.first][start.second] = 'a'
visited[end.first][end.second] = 0
to_visit.add(end)
val directions = setOf(Pair(0, 1), Pair(0, -1), Pair(-1, 0), Pair(1, 0))
var d = 1
while (to_visit.isNotEmpty()) {
val next = mutableSetOf<Pair<Int, Int>>()
for (p in to_visit) {
val height = map[p.first][p.second]
for (dir in directions) {
val x = p.first + dir.first
val y = p.second + dir.second
if (x >= 0 && x < n && y >= 0 && y < n) {
if (visited[x][y] == -1 && height <= map[x][y] + 1) {
visited[x][y] = d
next.add(Pair(x,y))
}
}
}
}
to_visit.clear()
to_visit.addAll(next)
++d
if (!multipleStart && visited[start.first][start.second] >= 0) {
return visited[start.first][start.second]
}
}
var min = Int.MAX_VALUE
for (i in 0 until n) {
for (j in 0 until n) {
if (map[i][j] == 'a' && visited[i][j] < min && visited[i][j] > 0) {
min = visited[i][j]
}
}
}
return min
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
println(part1(buildMap(testInput), false))
println(part1(buildMap(testInput), true))
val input = readInput("Day12")
println(part1(buildMap(input), false))
println(part1(buildMap(input), true))
}
| 0 |
Kotlin
| 0 | 0 |
eda0e2d6455dd8daa58ffc7292fc41d7411e1693
| 3,065 |
aoc-2022
|
Apache License 2.0
|
src/Day08.kt
|
haraldsperre
| 572,671,018 | false |
{"Kotlin": 17302}
|
fun main() {
fun isVisible(patch: List<List<Int>>, tree: Pair<Int, Int>): Boolean {
val (x, y) = tree
if (x == 0 || y == 0 || x == patch.size - 1 || y == patch[x].size - 1) {
return true
}
val treeHeight = patch[x][y]
return treeHeight > listOf(
patch.subList(0, x).maxOf { it[y] },
patch.subList(x + 1, patch.size).maxOf { it[y] },
patch[x].subList(0, y).max(),
patch[x].subList(y + 1, patch.size).max()
).min()
}
fun getScenicScore(patch: List<List<Int>>, tree: Pair<Int, Int>): Int {
val (x, y) = tree
val treeHeight = patch[x][y]
var score = 1
var tempScore = 0
if (x == 0 || y == 0 || x == patch.size - 1 || y == patch[x].size - 1) {
return 0
}
for (xi in (0 until x).reversed()) {
tempScore++
if (patch[xi][y] >= treeHeight) break
}
score *= tempScore
tempScore = 0
for (xi in (x + 1) until patch.size) {
tempScore++
if (patch[xi][y] >= treeHeight) break
}
score *= tempScore
tempScore = 0
for (yi in (0 until y).reversed()) {
tempScore++
if (patch[x][yi] >= treeHeight) break
}
score *= tempScore
tempScore = 0
for (yi in (y + 1) until patch[x].size) {
tempScore++
if (patch[x][yi] >= treeHeight) break
}
score *= tempScore
return score
}
fun part1(input: List<List<Int>>): Int {
val value = List(input.size) { y ->
List(input[y].size) { x ->
isVisible(input, x to y)
}
}
return value.sumOf { row -> row.count { it } }
}
fun part2(input: List<List<Int>>): Int {
val value = List(input.size) { y ->
List(input[y].size) { x ->
getScenicScore(input, x to y)
}
}
return value.maxOf{ it.maxOf{ it } }
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsIntLists("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInputAsIntLists("Day08")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
c4224fd73a52a2c9b218556c169c129cf21ea415
| 2,357 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day09.kt
|
RusticFlare
| 575,453,997 | false |
{"Kotlin": 4655}
|
fun main() {
fun part1(input: List<String>): Int {
return input.size
}
fun MutableList<MutableSet<Pair<Int, Int>>>.addPoint(point: Pair<Int, Int>): MutableSet<Pair<Int, Int>>? {
return if (none { basin -> point in basin }) {
mutableSetOf(point).also { add(it) }
} else {
null
}
}
fun List<List<Int>>.exploreBasin(
point: Pair<Int,Int>,
visited: MutableSet<Pair<Int, Int>> = mutableSetOf()
): Set<Pair<Int,Int>> {
listOf(
point.copy(first = point.first - 1),
point.copy(first = point.first + 1),
point.copy(second = point.second - 1),
point.copy(second = point.second + 1),
).filter { (row, col) -> getOrNull(row)?.getOrNull(col)?.let { it < 9 } == true }
.filter { visited.add(it) }
.forEach { exploreBasin(it, visited) }
return visited
}
fun part2(input: List<String>): Int {
val heightmap = input.map { depths -> depths.map { depth -> depth.digitToInt() } }
val basins = mutableListOf<Set<Pair<Int, Int>>>()
heightmap.asSequence().forEachIndexed { row, depths ->
depths.asSequence().withIndex()
.filter { (_, depth) -> depth < 9 }
.filter { (col) -> basins.none { (row to col) in it } }
.forEach { (col) -> basins.add(heightmap.exploreBasin(row to col)) }
}
val basinSizes = basins.map { it.size }
return basinSizes.sortedDescending().take(3).reduce(Int::times)
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day09_test")
// check(part1(testInput) == 1)
check(part2(testInput) == 1134)
val input = readLines("Day09")
// println(part1(input))
check(part2(input) == 1076922)
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
6ad85c80f771be683517fab804e9a933a90d5b41
| 1,897 |
advent-of-code-kotlin-2021
|
Apache License 2.0
|
src/main/kotlin/aoc2023/Day17.kt
|
Ceridan
| 725,711,266 | false |
{"Kotlin": 110767, "Shell": 1955}
|
package aoc2023
import java.util.*
class Day17 {
fun part1(input: String): Int {
val (grid, rows, cols) = parseInput(input)
return dijkstra(grid, Point(0, 0), Point(rows - 1, cols - 1), 1, 3)
}
fun part2(input: String): Int {
val (grid, rows, cols) = parseInput(input)
return dijkstra(grid, Point(0, 0), Point(rows - 1, cols - 1), 4, 10)
}
private fun dijkstra(grid: Map<Point, Int>, source: Point, target: Point, minStreak: Int, maxStreak: Int): Int {
val sourceState = StreakState(source, source, 0)
val costs = mutableMapOf(sourceState to 0)
val pq = PriorityQueue<QueueItem>()
pq.add(QueueItem(sourceState, 0))
while (pq.isNotEmpty()) {
val item = pq.poll()
if (item.state.point == target) return costs[item.state] ?: -1
val nextItems = calculateNextItems(grid, item, minStreak, maxStreak)
for (nextItem in nextItems) {
val currCost = costs.getOrDefault(nextItem.state, Int.MAX_VALUE)
if (nextItem.cost < currCost) {
costs[nextItem.state] = nextItem.cost
pq.add(nextItem)
}
}
}
return -1
}
private fun calculateNextItems(
grid: Map<Point, Int>,
item: QueueItem,
minStreak: Int,
maxStreak: Int
): List<QueueItem> {
val nextItems = mutableListOf<QueueItem>()
val currentDirection = (item.state.point - item.state.prevPoint).normalize()
val possibleDirections =
listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1)).filter { it != currentDirection.scale(-1) }
for (direction in possibleDirections) {
if (direction == currentDirection && item.state.streak == maxStreak) continue
val newStreak = if (direction == currentDirection) item.state.streak + 1 else minStreak
val streakDiff = if (direction == currentDirection) 1 else minStreak
val newPoint = item.state.point + direction.scale(streakDiff)
if (!grid.containsKey(newPoint)) continue
val newCost = item.cost + IntRange(1, streakDiff).sumOf {
val tmpPoint = item.state.point + direction.scale(it)
grid[tmpPoint]!!
}
val newStreakState = StreakState(newPoint, item.state.point, newStreak)
nextItems.add(QueueItem(newStreakState, newCost))
}
return nextItems
}
private fun parseInput(input: String): Triple<Map<Point, Int>, Int, Int> {
val grid = mutableMapOf<Point, Int>()
val lines = input.split('\n').filter { it.isNotEmpty() }
for (y in lines.indices) {
for (x in lines[y].indices) {
grid[y to x] = lines[y][x].digitToInt()
}
}
return Triple(grid, lines.size, lines[0].length)
}
data class QueueItem(val state: StreakState, val cost: Int) : Comparable<QueueItem> {
override fun compareTo(other: QueueItem): Int {
return cost.compareTo(other.cost)
}
}
data class StreakState(val point: Point, val prevPoint: Point, val streak: Int)
}
fun main() {
val day17 = Day17()
val input = readInputAsString("day17.txt")
println("17, part 1: ${day17.part1(input)}")
println("17, part 2: ${day17.part2(input)}")
}
| 0 |
Kotlin
| 0 | 0 |
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
| 3,422 |
advent-of-code-2023
|
MIT License
|
advent-of-code-2023/src/Day02.kt
|
osipxd
| 572,825,805 | false |
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
|
private const val DAY = "Day02"
fun main() {
val testInput = readInput("${DAY}_test")
val input = readInput(DAY)
"Part 1" {
part1(testInput) shouldBe 8
measureAnswer { part1(input) }
}
"Part 2" {
part2(testInput) shouldBe 2286
measureAnswer { part2(input) }
}
}
private fun part1(input: List<Game>): Int {
val bagColors = Colors(red = 12, green = 13, blue = 14)
return input
.filter { it.turns.all { colors -> colors in bagColors } }
.sumOf { it.id }
}
private fun part2(input: List<Game>): Int {
return input.sumOf {
val minColors = Colors(red = 0, green = 0, blue = 0)
for (colors in it.turns) minColors.extend(colors)
minColors.power
}
}
private fun readInput(name: String): List<Game> = readLines(name).map { line ->
val (rawId, rawTurns) = line.split(": ")
Game(
id = rawId.substringAfter(" ").toInt(),
turns = rawTurns.split("; ").map(::parseColors),
)
}
private fun parseColors(line: String): Colors {
val colors = line.split(", ")
.map { it.split(" ") }
.associate { (count, color) -> color to count.toInt() }
return Colors(
red = colors.getOrDefault("red", 0),
green = colors.getOrDefault("green", 0),
blue = colors.getOrDefault("blue", 0),
)
}
private data class Game(
val id: Int,
val turns: List<Colors>
)
@JvmInline
private value class Colors(private val colors: Array<Int>) {
var red: Int
get() = colors[0]
set(value) {
colors[0] = value
}
var green: Int
get() = colors[1]
set(value) {
colors[1] = value
}
var blue: Int
get() = colors[2]
set(value) {
colors[2] = value
}
val power: Int get() = red * green * blue
constructor(red: Int, green: Int, blue: Int) : this(arrayOf(red, green, blue))
operator fun contains(other: Colors): Boolean {
return other.red <= red && other.green <= green && other.blue <= blue
}
fun extend(colorsToFit: Colors) {
red = maxOf(red, colorsToFit.red)
green = maxOf(green, colorsToFit.green)
blue = maxOf(blue, colorsToFit.blue)
}
}
| 0 |
Kotlin
| 0 | 5 |
6a67946122abb759fddf33dae408db662213a072
| 2,265 |
advent-of-code
|
Apache License 2.0
|
src/aoc2022/Day02.kt
|
Playacem
| 573,606,418 | false |
{"Kotlin": 44779}
|
package aoc2022
import utils.readInput
private enum class RPS(val opponentLabel: String, val ourLabel: String, val selectionValue: Int) {
ROCK("A", "X", 1),
PAPER("B", "Y", 2),
SCISSOR("C", "Z", 3);
fun match(s: String): Boolean {
return s == opponentLabel || s == ourLabel
}
}
fun main() {
data class Match(val opponent: RPS, val self: RPS)
val rpsValues = RPS.values().toList()
fun parseDecision(s: String): RPS {
return RPS.values().find { it.match(s) } ?: error("Invalid string: '$s'")
}
fun Char.asRPS() = parseDecision(this.toString())
fun calculateMatchValue(match: Match): Int {
val (opponent, self) = match
if (opponent == self) {
return 3
}
val posDifference = self.ordinal - opponent.ordinal
if (posDifference in listOf(1, -2)) {
return 6
}
return 0
}
fun String.asMatch(): Match {
val (o, s) = this.split(" ", limit = 2).map { parseDecision(it) }
return Match(o, s)
}
fun Match.asTotalValue(): Int {
return calculateMatchValue(this) + self.selectionValue
}
fun String.outcomeAsMatchString(): String {
val outcome = this.last()
val o = this.first()
return when(outcome) {
'X' -> {
val losingRps = rpsValues[(o.asRPS().ordinal - 1 + rpsValues.size) % rpsValues.size]
"$o ${losingRps.ourLabel}"
}
'Y' -> "$o $o"
'Z' -> {
val winningRps = rpsValues[(o.asRPS().ordinal + 1 + rpsValues.size) % rpsValues.size]
"$o ${winningRps.ourLabel}"
}
else -> error("Invalid outcome: '$outcome'")
}
}
fun part1(input: List<String>): Int {
return input.map { it.asMatch() }.sumOf { it.asTotalValue() }
}
fun part2(input: List<String>): Int {
return input.map { it.outcomeAsMatchString() }.map { it.asMatch() }.sumOf { it.asTotalValue() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(2022, "Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput(2022, "Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
4ec3831b3d4f576e905076ff80aca035307ed522
| 2,325 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day08.kt
|
iam-afk
| 572,941,009 | false |
{"Kotlin": 33272}
|
fun main() {
val d = arrayOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)
fun List<String>.visible(i: Int, j: Int, h: Char) =
d.any { (di, dj) ->
generateSequence(i + di to j + dj) { (i, j) -> i + di to j + dj }
.takeWhile { (i, j) -> i in this.indices && j in this[i].indices }
.all { (i, j) -> this[i][j] < h }
}
fun part1(input: List<String>): Int = input.withIndex()
.flatMap { (i, row) -> row.withIndex().map { (j, h) -> Triple(i, j, h) } }
.count { (i, j, h) -> input.visible(i, j, h) }
fun List<String>.score(i: Int, j: Int, h: Char): Int =
d.map { (di, dj) ->
generateSequence(i + di to j + dj) { (i, j) -> if (this[i][j] >= h) null else i + di to j + dj }
.takeWhile { (i, j) -> i in this.indices && j in this[i].indices }
.count()
}.fold(1, Int::times)
fun part2(input: List<String>): Int = input.withIndex()
.flatMap { (i, row) -> row.withIndex().map { (j, h) -> Triple(i, j, h) } }
.maxOf { (i, j, h) -> input.score(i, j, h) }
// 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 |
b30c48f7941eedd4a820d8e1ee5f83598789667b
| 1,379 |
aockt
|
Apache License 2.0
|
src/Day18.kt
|
ambrosil
| 572,667,754 | false |
{"Kotlin": 70967}
|
fun main() {
data class Cube(val x: Int, val y: Int, val z: Int)
fun Cube.adjacents(): List<Cube> {
return listOf(
Cube(x+1, y, z), Cube(x-1, y, z),
Cube(x, y+1, z), Cube(x, y-1, z),
Cube(x, y, z+1), Cube(x, y, z-1),
)
}
fun parse(input: List<String>): Set<Cube> {
return input.map {
it.split(",").map { n -> n.toInt() }
}
.map { (x, y, z) -> Cube(x, y, z) }
.toSet()
}
fun part1(input: List<String>): Int {
val cubes = parse(input)
return cubes.sumOf { (it.adjacents() - cubes).size }
}
fun part2(input: List<String>): Int {
val cubes = parse(input)
val xRange = cubes.minOf { it.x } - 1..cubes.maxOf { it.x } + 1
val yRange = cubes.minOf { it.y } - 1..cubes.maxOf { it.y } + 1
val zRange = cubes.minOf { it.z } - 1..cubes.maxOf { it.z } + 1
val queue = ArrayDeque<Cube>().apply { add(Cube(xRange.first, yRange.first, zRange.first)) }
val seen = mutableSetOf<Cube>()
var sides = 0
queue.forEach { current ->
if (current !in seen) {
seen += current
current.adjacents()
.filter { it.x in xRange && it.y in yRange && it.z in zRange }
.forEach { adj -> if (adj in cubes) sides++ else queue.add(adj) }
}
}
return sides
}
val input = readInput("inputs/Day18")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
ebaacfc65877bb5387ba6b43e748898c15b1b80a
| 1,547 |
aoc-2022
|
Apache License 2.0
|
src/Day15.kt
|
andrikeev
| 574,393,673 | false |
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
|
import kotlin.math.abs
fun main() {
val regex = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
fun Pair<Int, Int>.distanceTo(that: Pair<Int, Int>): Int {
return abs(this.first - that.first) + abs(this.second - that.second)
}
fun String.parse(): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val (sX, sY, bX, bY) = regex.find(this)!!.groupValues.drop(1).map(String::toInt)
return Pair(sX, sY) to Pair(bX, bY)
}
fun part1(input: List<String>, level: Int): Int {
val covered = mutableSetOf<Pair<Int, Int>>()
input.forEach { line ->
val (sensor, beacon) = line.parse()
val distance = sensor.distanceTo(beacon)
for (x in (sensor.first - distance)..(sensor.first + distance)) {
val point = Pair(x, level)
if (point != beacon && sensor.distanceTo(point) <= distance) {
covered.add(point)
}
}
}
return covered.size
}
fun part2(input: List<String>, maxLevel: Int): Long {
val sensors = input.map { line ->
val (sensor, beacon) = line.parse()
sensor to sensor.distanceTo(beacon)
}.sortedBy { (sensor, beacon) -> sensor.first }
for (y in 0..maxLevel) {
var x = 0
sensors.forEach { (sensor, distance) ->
if (sensor.distanceTo(Pair(x, y)) <= distance) {
x = sensor.first + distance - abs(sensor.second - y) + 1
}
}
if (x <= maxLevel) {
return x * 4_000_000L + y
}
}
error("Not found")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10).also { println("part1 test: $it") } == 26)
check(part2(testInput, 20).also { println("part2 test: $it") } == 56_000_011L)
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 4000000))
}
| 0 |
Kotlin
| 0 | 1 |
1aedc6c61407a28e0abcad86e2fdfe0b41add139
| 2,094 |
aoc-2022
|
Apache License 2.0
|
src/Day12.kt
|
erikthered
| 572,804,470 | false |
{"Kotlin": 36722}
|
import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
data class Graph<T>(
val vertices: MutableSet<T> = mutableSetOf(),
val edges: MutableMap<T, Set<T>> = mutableMapOf(),
val weights: MutableMap<Pair<T, T>, Int> = mutableMapOf()
)
fun Char.toElevation() = when(this) {
'S' -> 'a'.code
'E' -> 'z'.code
else -> this.code
}
data class Point(
val x: Int,
val y: Int,
val elevation: Int
)
fun List<String>.getPoint(x: Int, y: Int): Point {
return Point(x, y, this[y][x].toElevation())
}
fun buildGraph(input: List<String>, remove: (current: Point, next: Point) -> Boolean): Graph<Point> {
val graph = Graph<Point>()
input.forEachIndexed { y, row ->
row.forEachIndexed { x, c ->
val point = Point(x, y, c.toElevation())
val edges = mutableSetOf<Point>()
if(x != input.first().lastIndex) edges.add(input.getPoint(x+1, y))
if(x != 0) edges.add(input.getPoint(x-1, y))
if(y != input.lastIndex) edges.add(input.getPoint(x, y+1))
if(y != 0) edges.add(input.getPoint(x, y-1))
edges.removeIf { dest -> remove(point, dest)}
graph.vertices.add(point)
graph.edges[point] = edges
edges.forEach { e ->
graph.weights[point to e] = 1
}
}
}
return graph
}
fun <T> dijkstra(graph: Graph<T>, start: T): Map<T, T?> {
val s = mutableSetOf<T>()
val delta = graph.vertices.associateWith { Int.MAX_VALUE }.toMutableMap()
delta[start] = 0
val previous: MutableMap<T, T?> = graph.vertices.associateWith { null }.toMutableMap()
while (s != graph.vertices) {
val v: T = delta
.filter { !s.contains(it.key) }
.minBy { it.value }
.key
graph.edges.getValue(v).minus(s).forEach { neighbor ->
val newPath = delta.getValue(v) + graph.weights.getValue(Pair(v, neighbor))
if(newPath < delta.getValue(neighbor)) {
delta[neighbor] = newPath
previous[neighbor] = v
}
}
s.add(v)
}
return previous.toMap()
}
fun <T> shortestPath(tree: Map<T, T?>, start: T, end: T): List<T> {
fun pathTo(start: T, end: T): List<T> {
if (tree[end] == null) return listOf(end)
return listOf(pathTo(start, tree[end]!!), listOf(end)).flatten()
}
return pathTo(start, end)
}
fun part1(input: List<String>): Int {
val graph = buildGraph(input) { current, next ->
next.elevation - current.elevation > 1
}
val startY = input.indexOfFirst { it.contains('S') }
val startX = input[startY].toCharArray().indexOfFirst { it == 'S' }
val start = input.getPoint(startX, startY)
val tree = dijkstra(graph, start)
val endY = input.indexOfFirst { it.contains('E') }
val endX = input[endY].toCharArray().indexOfFirst { it == 'E' }
val end = input.getPoint(endX, endY)
val path = shortestPath(tree, start, end)
return path.size - 1
}
fun part2(input: List<String>): Int {
val graph = buildGraph(input) { current, next ->
current.elevation - next.elevation > 1
}
val endY = input.indexOfFirst { it.contains('E') }
val endX = input[endY].toCharArray().indexOfFirst { it == 'E' }
val end = input.getPoint(endX, endY)
val tree = dijkstra(graph, end)
val candidates = graph.vertices
.filter { it.elevation == 'a'.code }
val paths = candidates
.mapNotNull { p ->
val path = shortestPath(tree, end, p)
if(path.containsAll(listOf(p, end))) {
path
} else {
null
}
}
return paths.minOf { it.size - 1 }
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
3946827754a449cbe2a9e3e249a0db06fdc3995d
| 4,341 |
aoc-2022-kotlin
|
Apache License 2.0
|
src/Day08.kt
|
LauwiMeara
| 572,498,129 | false |
{"Kotlin": 109923}
|
fun main() {
fun calculateViewingDistance(range: IntProgression, isRowIndex: Boolean, input: List<List<Int>>, row: Int, col: Int): Int {
var viewingDistance = 0
for (i in range) {
viewingDistance++
if (isRowIndex && input[i][col] >= input[row][col] ||
!isRowIndex && input[row][i] >= input[row][col]) {
break
}
}
return viewingDistance
}
fun part1(input: List<List<Int>>): Int {
var numOfVisibleTrees = 0
for (row in input.indices) {
for (col in input.first().indices) {
// Trees on the outside border are always visible.
if (row == 0 || row == input.size - 1 ||
col == 0 || col == input.first().size - 1) {
numOfVisibleTrees++
} else {
// Trees within are visible if any trees up, down, left or right are higher.
if (input.subList(0, row).isNotEmpty() && input.subList(0, row).all{it[col] < input[row][col]} ||
input.subList(row + 1, input.size).isNotEmpty() && input.subList(row + 1, input.size).all{it[col] < input[row][col]} ||
input[row].subList(0, col).isNotEmpty() && input[row].subList(0, col).all{it < input[row][col]} ||
input[row].subList(col + 1, input[row].size).isNotEmpty() && input[row].subList(col + 1, input[row].size).all{it < input[row][col]}) {
numOfVisibleTrees++
}
}
}
}
return numOfVisibleTrees
}
fun part2(input: List<List<Int>>): Int {
val scenicScores = mutableListOf<Int>()
for (row in input.indices) {
for (col in input.first().indices) {
val up = calculateViewingDistance((row - 1 downTo 0), true, input, row, col)
val down = calculateViewingDistance((row + 1 until input.size), true, input, row, col)
val left = calculateViewingDistance((col - 1 downTo 0), false, input, row, col)
val right = calculateViewingDistance((col + 1 until input.first().size), false, input, row, col)
scenicScores.add(up * down * left * right)
}
}
return scenicScores.max()
}
val input = readInputAsStrings("Day08")
.map{line -> line.toCharArray()
.map{ it.digitToInt() }}
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
34b4d4fa7e562551cb892c272fe7ad406a28fb69
| 2,539 |
AoC2022
|
Apache License 2.0
|
src/poyea/aoc/mmxxii/day11/Day11.kt
|
poyea
| 572,895,010 | false |
{"Kotlin": 68491}
|
package poyea.aoc.mmxxii.day11
import poyea.aoc.utils.readInput
fun simulate(input: String, rounds: Int): Long {
val monkeys = input.split("\n\n").map { it.split("\n") }
val items = monkeys.map {
it[1].split(":")[1].split(",").map { iy -> iy.trim().toLong() }.toMutableList()
}
val ops = monkeys.map { it[2].split(":")[1].trim().split(" = ")[1] }
val tests = monkeys.map { it[3].split("Test: divisible by ")[1] }.map { it.toLong() }
val mod = tests.reduce(Long::times) // this is... basically LCM of tests
val trueMonkeys = monkeys.map { it[4].split("If true: throw to monkey ")[1] }.map { it.toInt() }
val falseMonkeys = monkeys.map { it[5].split("If false: throw to monkey ")[1] }.map { it.toInt() }
val timesInspected = MutableList(trueMonkeys.size) { 0L }
for (round in 1..rounds) {
for ((i, monkeyItems) in items.withIndex()) {
fun applyOperator(n: Long): Long {
val op = ops[i].split(" ")
return when (op[2]) {
"old" -> n * n
else -> {
if (op[1] == "*") {
n * op[2].toLong()
} else {
n + op[2].toLong()
}
}
}
}
for (item: Long in monkeyItems) {
val currentLevel = if (rounds > 2023) applyOperator(item) % mod else applyOperator(item) / 3L
if ((currentLevel % tests[i]) == 0L) {
items[trueMonkeys[i]].add(currentLevel)
} else {
items[falseMonkeys[i]].add(currentLevel)
}
}
timesInspected[i] = timesInspected[i] + monkeyItems.size
monkeyItems.clear()
}
}
return timesInspected.sortedDescending().take(2).reduce { acc, i -> acc * i }
}
fun part1(input: String): Long {
return simulate(input, 20)
}
fun part2(input: String): Long {
return simulate(input, 10000)
}
fun main() {
println(part1(readInput("Day11")))
println(part2(readInput("Day11")))
}
| 0 |
Kotlin
| 0 | 1 |
fd3c96e99e3e786d358d807368c2a4a6085edb2e
| 2,157 |
aoc-mmxxii
|
MIT License
|
src/Day08.kt
|
RandomUserIK
| 572,624,698 | false |
{"Kotlin": 21278}
|
fun List<String>.toIntMatrix(): Array<Array<Int>> =
map { row ->
row.map(Char::digitToInt).toTypedArray()
}.toTypedArray()
fun Array<Array<Int>>.neighborsFrom(row: Int, col: Int): List<List<Int>> =
listOf(
(0 until row).map { this[it][col] }.asReversed(), // north
(row + 1..lastIndex).map { this[it][col] }, // south
this[row].slice(col + 1..lastIndex), // east
this[row].slice(0 until col).asReversed() // west
)
fun Array<Array<Int>>.isVisible(row: Int, col: Int): Boolean =
neighborsFrom(row, col).any { neighbors ->
neighbors.all { it < this[row][col] }
}
fun List<Int>.product(): Int =
reduce { acc, i -> acc * i }
fun List<Int>.numberOfSmallerTrees(referenceHeight: Int): Int {
var result = 0
for (item in this) {
++result
if (item >= referenceHeight)
break
}
return result
}
fun Array<Array<Int>>.scenicScoreFrom(row: Int, col: Int): Int =
neighborsFrom(row, col)
.map { neighbors -> neighbors.numberOfSmallerTrees(this[row][col]) }
.product()
fun main() {
fun part1(input: List<String>): Int {
var visibleTrees = 4 * input.size - 4 // trees around the edge
val treeMap = input.toIntMatrix()
(1 until treeMap.lastIndex).forEach { row ->
visibleTrees += (1 until treeMap.lastIndex).count { col -> treeMap.isVisible(row, col) }
}
return visibleTrees
}
fun part2(input: List<String>): Int {
val treeMap = input.toIntMatrix()
return (1 until treeMap.lastIndex).maxOf { row ->
(1 until treeMap.lastIndex).maxOf { col -> treeMap.scenicScoreFrom(row, col) }
}
}
val input = readInput("inputs/day08_input")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
f22f10da922832d78dd444b5c9cc08fadc566b4b
| 1,624 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day02.kt
|
WilsonSunBritten
| 572,338,927 | false |
{"Kotlin": 40606}
|
fun main() {
fun part1(input: List<String>): Int {
return input.map { round ->
val split = round.split(" ")
val opponentPlay = opponentPlay[split.first()] ?: error("bad input")
val myPlay = myPlay[split[1]] ?: error("bad input")
gameScore(opponentPlay, myPlay)
}.sum()
}
fun part2(input: List<String>): Int {
return input.map { round ->
val split = round.split(" ")
val opponent = opponentPlay[split.first()] ?: error("")
val me = when(split[1]) {
"X" -> Result.LOSE
"Y" -> Result.DRAW
"Z" -> Result.WIN
else -> error("")
}
val myPlay = when (me) {
Result.WIN -> Play.values().first { it.ordinal == (opponent.ordinal + 1) % 3 }
Result.DRAW -> opponent
Result.LOSE -> Play.values().first { (it.ordinal + 1) % 3 == opponent.ordinal }
}
me.score + myPlay.score
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
println(part2(testInput))
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class Play(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
}
private fun gameScore(opponent: Play, me: Play): Int {
if (opponent == me) {
return me.score + Result.DRAW.score
} else if (opponent.ordinal == (me.ordinal + 1) % 3) {
return me.score + Result.LOSE.score
} else {
return me.score + Result.WIN.score
}
}
enum class Result(val score: Int) {
WIN(6), LOSE(0), DRAW(3);
}
val myPlay = mapOf(
"X" to Play.ROCK,
"Y" to Play.PAPER,
"Z" to Play.SCISSORS
)
val opponentPlay = mapOf(
"A" to Play.ROCK,
"B" to Play.PAPER,
"C" to Play.SCISSORS
)
| 0 |
Kotlin
| 0 | 0 |
363252ffd64c6dbdbef7fd847518b642ec47afb8
| 1,992 |
advent-of-code-2022-kotlin
|
Apache License 2.0
|
2k23/aoc2k23/src/main/kotlin/11.kt
|
papey
| 225,420,936 | false |
{"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117}
|
package d11
import input.read
import kotlin.math.abs
import kotlin.math.min
fun main() {
println("Part 1: ${part1(read("11.txt"))}")
println("Part 2: ${part2(read("11.txt"))}")
}
fun part1(input: List<String>): Long {
val galaxy = Supercluster(input)
return galaxy.eachGalaxyPair().sumOf(galaxy::distance)
}
fun part2(input: List<String>): Long {
val galaxy = Supercluster(input)
return galaxy.eachGalaxyPair().sumOf { galaxy.distance(it, 1000000L) }
}
class Point(val x: Long, val y: Long)
class Supercluster(input: List<String>) {
private val EMPTY_SPACE = '.'
private val GALAXY = '#'
val map = input.map { it.toCharArray().toMutableList() }.toMutableList()
private val h = map.size
private val w = map.first().size
private val extraLines = (0L..<h).filter { y ->
(0L..<w).all { x ->
getValue(Point(x, y)) == EMPTY_SPACE
}
}
private val extraRows = (0L..<w).filter { x ->
(0L..<h).all { y ->
getValue(Point(x, y)) == EMPTY_SPACE
}
}
private val galaxies = (0L..<h).flatMap { y ->
(0L..<w).filter { x ->
getValue(Point(x, y)) == GALAXY
}.map { Point(it, y) }
}
fun getValue(point: Point): Char = map[point.y.toInt()][point.x.toInt()]
fun eachGalaxyPair(): List<Pair<Point, Point>> = galaxies.indices.flatMap { i ->
(i.inc()..<galaxies.size).map { j ->
Pair(galaxies[i], galaxies[j])
}
}
fun distance(galaxies: Pair<Point, Point>, jump: Long = 2L): Long {
val (g1, g2) = galaxies
val ox = min(g2.x, g1.x)
val oy = min(g2.y, g1.y)
val dx = abs(g2.x - g1.x)
val dy = abs(g2.y - g1.y)
val d = dx + dy
val jumps = (ox..ox + dx).count { x -> extraRows.contains(x) } +
(oy..oy + dy).count { y -> extraLines.contains(y) }
return d + jumps * (jump - 1)
}
}
| 0 |
Rust
| 0 | 3 |
cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5
| 1,950 |
aoc
|
The Unlicense
|
src/Day07.kt
|
purdyk
| 572,817,231 | false |
{"Kotlin": 19066}
|
sealed class Node(val name: String) {
class File(name:String, val length: Int): Node(name)
class Dir(name: String, val parent: Dir?, val children: MutableList<Node> = mutableListOf()): Node(name) {
fun select(from: String): Dir {
return if (from == "..") {
parent!!
} else {
children.first { it.name == from } as Dir
}
}
}
}
fun Node.size(): Int {
return when (this) {
is Node.File -> this.length
is Node.Dir -> this.children.sumOf { it.size() }
}
}
fun cmd(line: String, parent: Node.Dir): Node.Dir {
return when (line[2]) {
'c' -> parent.select(line.split(" ")[2])
'd' -> parent
else -> parent
}
}
fun entry(line: String, parent: Node.Dir): Node {
val (a,b) = line.split(" ")
return if (a == "dir") {
Node.Dir(b, parent)
} else {
Node.File(b, a.toInt())
}
}
fun parse(input: List<String>): Node {
val root = Node.Dir("/", null)
var cur = root
input.drop(1).forEach {
when (it[0]) {
'$' -> cur = cmd(it, cur)
else -> cur.children.add(entry(it, cur))
}
}
return root
}
fun print(node: Node, prefix: String = "") {
print("$prefix${node.name}\n")
(node as? Node.Dir)?.also {
it.children.forEach { print(it, "$prefix ") }
}
}
fun Node.walkDirectories(): Sequence<Node.Dir> {
val subDirs = ((this as? Node.Dir)?.children ?: emptyList<Node>())
.filterIsInstance<Node.Dir>()
.iterator()
return sequence {
while (subDirs.hasNext()) {
val dir = subDirs.next()
yield(dir)
yieldAll(dir.walkDirectories())
}
}
}
fun main() {
fun part1(input: List<String>): String {
val root = parse(input)
val smalls = root.walkDirectories().filter { it.size() <= 100000 }.toList()
return smalls.sumOf { it.size() }.toString()
}
fun part2(input: List<String>): String {
val total = 70000000
val needed = 30000000
val root = parse(input)
val used = root.size()
val free = total - used
val toFree = needed - free
val bigs = root.walkDirectories().filter { it.size() >= toFree }.toList()
val selected = bigs.minBy { it.size() }
return selected.size().toString()
}
val day = "07"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test").split("\n")
println("Test: ")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == "95437")
check(part2(testInput) == "24933642")
val input = readInput("Day${day}").split("\n")
println("\nProblem: ")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
02ac9118326b1deec7dcfbcc59db8c268d9df096
| 2,859 |
aoc2022
|
Apache License 2.0
|
src/day13/Day13.kt
|
seastco
| 574,758,881 | false |
{"Kotlin": 72220}
|
package day13
import readText
import org.json.JSONArray
import readLines
import kotlin.math.min
class Packet(val packet: JSONArray) : Comparable<Packet> {
override fun compareTo(other: Packet): Int {
return compare(this.packet, other.packet)
}
/*
The comparison algorithm is based on the following logic:
- If both values are integers, the lower integer should come first. Meaning if b > a, input is in the right order.
- If both values are lists, compare the values within the lists. If either list is exhausted, the input is in the
right order if b.length() > a.length().
- If exactly one value is an integer, convert the integer to a JSONArray and retry the comparison.
*/
private fun compare(a: Any, b: Any): Int {
if (a is Int && b is Int) {
return b.compareTo(a)
} else if (a is JSONArray && b is JSONArray) {
(0 until min(a.length(), b.length())).forEach {
val result = compare(a[it], b[it])
if (result != 0) {
return result
}
}
return b.length().compareTo(a.length())
} else {
if (a is Int) {
return compare(JSONArray("[$a]"), b)
} else {
return compare(a, JSONArray("[$b]"))
}
}
}
}
private fun part1(input: String): Int {
val pairs = input
.split("\n\n")
.map { it.split("\n").map { packet -> Packet(JSONArray(packet)) } }.toMutableList()
val sum = pairs
.map { pair -> pair[0].compareTo(pair[1]) }
.withIndex()
.sumOf { if (it.value == 1) it.index+1 else 0 }
return sum
}
private fun part2(input: List<String>): Int {
val packets = input
.filter { it.isNotEmpty() }
.flatMap { it.split("\n").map { packet -> Packet(JSONArray(packet)) } }
.toMutableList()
val dividerPacket2 = Packet(JSONArray("[[2]]"))
val dividerPacket6 = Packet(JSONArray("[[6]]"))
val sortedPackets = (packets + dividerPacket2 + dividerPacket6).sortedDescending()
return (sortedPackets.indexOf(dividerPacket2) + 1) * (sortedPackets.indexOf(dividerPacket6) + 1)
}
fun main() {
println(part1(readText("day13/test")))
println(part2(readLines("day13/test")))
println(part1(readText("day13/input")))
println(part2(readLines("day13/input")))
}
| 0 |
Kotlin
| 0 | 0 |
2d8f796089cd53afc6b575d4b4279e70d99875f5
| 2,414 |
aoc2022
|
Apache License 2.0
|
src/day09/Day09.kt
|
dkoval
| 572,138,985 | false |
{"Kotlin": 86889}
|
package day09
import readInput
import kotlin.math.abs
private const val DAY_ID = "09"
private enum class Direction(val dx: Int, val dy: Int) {
U(1, 0), D(-1, 0), L(0, -1), R(0, 1),
UL(1, -1), UR(1, 1), DL(-1, -1), DR(-1, 1)
}
private data class Knot(
var row: Int,
var col: Int
) {
fun move(d: Direction) {
row += d.dx
col += d.dy
}
fun isAdjacent(that: Knot): Boolean =
abs(row - that.row) <= 1 && abs(col - that.col) <= 1
}
fun main() {
fun solve(input: List<String>, n: Int): Int {
val knots = Array(n) { Knot(0, 0) }
val visited = mutableSetOf<Pair<Int, Int>>().also { it += 0 to 0 }
fun move(d: Direction, steps: Int) {
repeat(steps) {
// move head
knots[0].move(d)
// move remaining knots, if needed
for (i in 1 until n) {
val head = knots[i - 1]
val tail = knots[i]
if (tail.isAdjacent(head)) continue
when {
// head and tail are in the same row
tail.row == head.row -> tail.move(if (head.col > tail.col) Direction.R else Direction.L)
// head and tail are in the same column
tail.col == head.col -> tail.move(if (head.row > tail.row) Direction.U else Direction.D)
// head and tail aren't in the same row or column, therefore move tail one step diagonally to keep up
else -> {
if (head.row > tail.row) {
tail.move(if (tail.col < head.col) Direction.UR else Direction.UL)
} else {
tail.move(if (tail.col < head.col) Direction.DR else Direction.DL)
}
}
}
}
visited += knots[n - 1].row to knots[n - 1].col
}
}
val data = input.map { line ->
val (d, steps) = line.split(" ")
enumValueOf<Direction>(d) to steps.toInt()
}
data.forEach { (d, steps) -> move(d, steps) }
return visited.size
}
fun part1(input: List<String>): Int = solve(input, 2)
fun part2(input: List<String>): Int = solve(input, 10)
// test if implementation meets criteria from the description, like:
val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
check(part2(readInput("day${DAY_ID}/Day${DAY_ID}_test_part2")) == 36)
val input = readInput("day${DAY_ID}/Day$DAY_ID")
println(part1(input)) // answer = 6037
println(part2(input)) // answer = 2485
}
| 0 |
Kotlin
| 1 | 0 |
791dd54a4e23f937d5fc16d46d85577d91b1507a
| 2,824 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/Day08.kt
|
D000L
| 575,350,411 | false |
{"Kotlin": 23716}
|
fun main() {
fun part1(input: List<String>): Int {
val map = input.map { it.toCharArray().map { it.digitToInt() } }
fun find(y: Int, x: Int): Boolean {
val treeHeight = map[y][x]
val dir = listOf(1 to 0, -1 to 0, 0 to 1, 0 to -1)
dir.forEach { (dx, dy) ->
var currentX = x
var currentY = y
do {
currentX += dx
currentY += dy
val targetTreeHeight = map.getOrNull(currentY)?.getOrNull(currentX) ?: return true
} while (treeHeight > targetTreeHeight)
}
return false
}
return map.indices.flatMap { y -> map[0].indices.map { x -> y to x } }.count { (y, x) -> find(y, x) }
}
fun part2(input: List<String>): Int {
val map = input.map { it.toCharArray().map { it.digitToInt() } }
fun find(y: Int, x: Int): Int {
val treeHeight = map[y][x]
val dir = listOf(1 to 0, -1 to 0, 0 to 1, 0 to -1)
return dir.map { (dy, dx) ->
var currentX = x
var currentY = y
var count = 0
do {
currentX += dx
currentY += dy
val targetTreeHeight = map.getOrNull(currentY)?.getOrNull(currentX) ?: break
count++
} while (treeHeight > targetTreeHeight)
count
}.fold(1) { total, score -> total * score }
}
return map.indices.flatMap { y -> map[0].indices.map { x -> y to x } }.maxOf { (y, x) -> find(y, x) }
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
b733a4f16ebc7b71af5b08b947ae46afb62df05e
| 1,762 |
adventOfCode
|
Apache License 2.0
|
src/day18/Day18.kt
|
andreas-eberle
| 573,039,929 | false |
{"Kotlin": 90908}
|
package day18
import readInput
import java.lang.Integer.max
import java.util.ArrayDeque
const val day = "18"
operator fun Triple<Int, Int, Int>.plus(o: Triple<Int, Int, Int>) = Triple(first + o.first, second + o.second, third + o.third)
operator fun Triple<Int, Int, Int>.plus(i: Int) = Triple(first + i, second + i, third + i)
fun Collection<Triple<Int, Int, Int>>.maxAll() = reduce { acc, triple -> Triple(max(acc.first, triple.first), max(acc.second, triple.second), max(acc.third, triple.third)) }
val sideOffsets = listOf(
Triple(1, 0, 0),
Triple(-1, 0, 0),
Triple(0, 1, 0),
Triple(0, -1, 0),
Triple(0, 0, 1),
Triple(0, 0, -1),
)
fun List<String>.parseCubes(): Set<Triple<Int, Int, Int>> = map { it.split(",") }.map { (x, y, z) -> Triple(x.toInt(), y.toInt(), z.toInt()) }.toSet()
fun main() {
fun calculatePart1Score(input: List<String>): Int {
val allCubes = input.parseCubes()
return allCubes.asSequence()
.flatMap { cube -> sideOffsets.map { cube + it } }
.filter { !allCubes.contains(it) }
.count()
}
fun calculatePart2Score(input: List<String>): Int {
val allCubes = input.parseCubes()
val maxAll = allCubes.maxAll() + 1
val queue = ArrayDeque<Triple<Int, Int, Int>>()
queue.add(Triple(0, 0, 0) )
val outsideAir = mutableSetOf<Triple<Int, Int, Int>>()
while (queue.isNotEmpty()) {
val current = queue.poll()
val validNeighbors = sideOffsets.asSequence()
.map { current + it }
.filter { (x, y, z) -> x in (-1..maxAll.first) && y in (-1..maxAll.second) && z in (-1..maxAll.third) }
.filter { !allCubes.contains(it) }
.filter { !outsideAir.contains(it) }
.toList()
outsideAir.addAll(validNeighbors)
queue.addAll(validNeighbors)
}
return allCubes.asSequence()
.flatMap { cube -> sideOffsets.map { cube + it } }
.filter { !allCubes.contains(it) }
.filter { outsideAir.contains(it) }
.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
println("Part1 test points: $part1TestPoints")
check(part1TestPoints == 64)
val part1points = calculatePart1Score(input)
println("Part1 points: $part1points")
val part2TestPoints = calculatePart2Score(testInput)
println("Part2 test points: $part2TestPoints")
check(part2TestPoints == 58)
val part2points = calculatePart2Score(input)
println("Part2 points: $part2points")
}
| 0 |
Kotlin
| 0 | 0 |
e42802d7721ad25d60c4f73d438b5b0d0176f120
| 2,802 |
advent-of-code-22-kotlin
|
Apache License 2.0
|
codeforces/vk2021/qual/e12.kt
|
mikhail-dvorkin
| 93,438,157 | false |
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
|
package codeforces.vk2021.qual
private fun permutation(comparisons: List<Boolean>, n: Int): Pair<Int, List<Int>> {
var pos = 0
fun permutation(m: Int): List<Int> {
if (m <= 1) return List(m) { 0 }
val left = m / 2
val right = m - left
val permutationLeft = permutation(left)
val permutationRight = permutation(right)
val leftNumbers = mutableListOf<Int>()
val rightNumbers = mutableListOf<Int>()
for (i in 0 until m) {
val half = if (leftNumbers.size < left && rightNumbers.size < right) {
if (comparisons.getOrElse(pos++) { false }) rightNumbers else leftNumbers
} else if (leftNumbers.size < left) leftNumbers else rightNumbers
half.add(i)
}
return permutationLeft.map { leftNumbers[it] } + permutationRight.map { rightNumbers[it] }
}
val permutation = permutation(n)
return pos - comparisons.size to permutation
}
private fun solve(comparisons: List<Boolean>): List<Int> {
var low = 0
var high = comparisons.size + 2
while (low + 1 < high) {
val n = (low + high) / 2
val (error, permutation) = permutation(comparisons, n)
if (error == 0) return permutation
if (error < 0) low = n else high = n
}
for (d in 0..comparisons.size) for (sign in -1..1 step 2) {
val n = low + sign * d
if (n <= 0) continue
val (error, permutation) = permutation(comparisons, n)
if (error == 0) return permutation
}
error("")
}
fun main() {
val comparisons = readLn().map { it == '1' }
val permutation = solve(comparisons)
println(permutation.size)
println(permutation.joinToString(" ") { (it + 1).toString() })
}
private fun readLn() = readLine()!!
| 0 |
Java
| 1 | 9 |
30953122834fcaee817fe21fb108a374946f8c7c
| 1,598 |
competitions
|
The Unlicense
|
src/Day14.kt
|
freszu
| 573,122,040 | false |
{"Kotlin": 32507}
|
fun main() {
fun parse(lines: List<String>): Set<Position> = lines.map { line ->
line.split(" -> ")
.map {
val (x, y) = it.split(",")
x.toInt() to y.toInt()
}
.windowed(2)
.map { (p1, p2) -> p1.walkHorizontallyOrVertically(p2).toList() }
.flatten()
}
.flatten()
.toSortedSet(compareBy<Pair<Int, Int>> { it.first }.thenBy { it.second })
tailrec fun sandFall(
caveMap: Set<Position>,
lowestYIsFloor: Boolean,
particle: Position = 500 to 0,
lowestY: Int = caveMap.maxOf { it.y }
): Set<Position> {
val below = particle.copy(second = particle.y + 1)
return when {
particle in caveMap -> caveMap
below.y > lowestY -> if (lowestYIsFloor) {
sandFall(caveMap + particle, lowestYIsFloor, lowestY = lowestY)
} else {
caveMap
}
below !in caveMap -> sandFall(caveMap, lowestYIsFloor, below, lowestY)
else -> {
val left = below.copy(first = below.x - 1)
val right = below.copy(first = below.x + 1)
when {
left in caveMap && right in caveMap -> sandFall(
caveMap + particle, lowestYIsFloor, lowestY = lowestY
)
left !in caveMap -> sandFall(caveMap, lowestYIsFloor, left, lowestY)
right !in caveMap -> sandFall(caveMap, lowestYIsFloor, right, lowestY)
else -> error("Should not happen")
}
}
}
}
fun part1(lines: List<String>): Int {
val caveMap = parse(lines)
val sandFall = sandFall(caveMap, lowestYIsFloor = false)
return sandFall.count() - caveMap.count()
}
fun part2(lines: List<String>): Int {
val caveMap = parse(lines)
val sandFall = sandFall(
caveMap, lowestY = (caveMap.maxOf { it.y } + 1), lowestYIsFloor = true
)
return sandFall.count() - caveMap.count()
}
val testInput = readInput("Day14_test")
val input = readInput("Day14")
check(part1(testInput) == 24)
println(part1(input))
check(part2(testInput) == 93)
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
2f50262ce2dc5024c6da5e470c0214c584992ddb
| 2,341 |
aoc2022
|
Apache License 2.0
|
src/main/kotlin/net/wrony/aoc2023/a3/Main.kt
|
kopernic-pl
| 727,133,267 | false |
{"Kotlin": 52043}
|
package net.wrony.aoc2023.a3
import kotlin.io.path.Path
import kotlin.io.path.readText
data class PartNumber(val row: Int, val range: IntRange, val value: Int) {
fun partNeighbourhood(size: Int): Sequence<Pair<Int, Int>> {
return sequence {
yield(Pair(row, range.first - 1))
yield(Pair(row, range.last + 1))
yieldAll((range.first - 1..range.last + 1).map { Pair(row - 1, it) })
yieldAll((range.first - 1..range.last + 1).map { Pair(row + 1, it) })
}.filter { it.first >= 0 && it.second >= 0 && it.first < size && it.second < size }
}
fun isInNeighbourhood(size: Int, row: Int, col: Int): Boolean {
return partNeighbourhood(size).any { it.first == row && it.second == col }
}
}
fun isFakePart(part: PartNumber, a: Array<CharArray>): Boolean {
val neighbours = part.partNeighbourhood(a.size)
return neighbours.all { a[it.first][it.second].isDigit() || a[it.first][it.second] == '.' }
}
fun findGears(a: Array<CharArray>): Sequence<Pair<Int, Int>> {
return sequence {
yieldAll(a.indices.flatMap { row ->
a[row].indices.map { col ->
Pair(row, col)
}
}.filter { a[it.first][it.second] == '*' })
}
}
fun main() {
val input = Path("src/main/resources/3.txt").readText().lines()
val size = input[0].length
val a = Array(size) { i -> input[i].toCharArray() }
val allParts = input.flatMapIndexed { lineIdx, line ->
Regex("\\d+").findAll(line).map { PartNumber(lineIdx, it.range, it.value.toInt()) }
}
println("Sum of real parts on the schematic: " + allParts.filter { !isFakePart(it, a) }
.sumOf { it.value })
val allPossibleGearPositions = findGears(a)
fun hasExactlyTwoParts(gearPosition: Pair<Int, Int>): Boolean {
return allParts.count {
it.isInNeighbourhood(
size, gearPosition.first, gearPosition.second
)
} == 2
}
fun getTwoPartsOfGear(gearPosition: Pair<Int, Int>): List<PartNumber> {
return allParts.filter {
it.isInNeighbourhood(
size, gearPosition.first, gearPosition.second
)
}.take(2)
}
println("Sum of real parts on the schematic: " + allPossibleGearPositions.filter {
hasExactlyTwoParts(
it
)
}.map { getTwoPartsOfGear(it) }.map { (first, second) -> first.value * second.value }.sum())
}
| 0 |
Kotlin
| 0 | 0 |
1719de979ac3e8862264ac105eb038a51aa0ddfb
| 2,488 |
aoc-2023-kotlin
|
MIT License
|
src/main/kotlin/de/nosswald/aoc/days/Day02.kt
|
7rebux
| 722,943,964 | false |
{"Kotlin": 34890}
|
package de.nosswald.aoc.days
import de.nosswald.aoc.Day
// https://adventofcode.com/2023/day/2
object Day02 : Day<Int>(2, "Cube Conundrum") {
private data class Game(val id: Int, val sets: List<Set>)
private data class Set(val cubes: MutableMap<Color, Int>)
private enum class Color { RED, GREEN, BLUE }
private fun parseGames(input: List<String>): List<Game> {
return input.mapIndexed { index, line ->
val sets = buildList {
line.split(": ")[1].split("; ").forEach { set ->
val current = Set(mutableMapOf())
set.split(", ").forEach {
val (amount, color) = it.split(" ")
when (color) {
"red" -> current.cubes[Color.RED] = amount.toInt()
"green" -> current.cubes[Color.GREEN] = amount.toInt()
"blue" -> current.cubes[Color.BLUE] = amount.toInt()
else -> error("Invalid color: $color")
}
}
this.add(current)
}
}
return@mapIndexed Game(index + 1, sets)
}
}
override fun partOne(input: List<String>): Int {
val maxCubesByColor = mapOf(
Color.RED to 12,
Color.GREEN to 13,
Color.BLUE to 14,
)
return parseGames(input).sumOf { game ->
game.sets.forEach { set ->
if (set.cubes.any { (color, amount) -> amount > maxCubesByColor[color]!! })
return@sumOf 0
}
return@sumOf game.id
}
}
override fun partTwo(input: List<String>): Int {
return parseGames(input).sumOf { game ->
val minCubesNeededByColor = mutableMapOf(
Color.RED to 0,
Color.GREEN to 0,
Color.BLUE to 0,
)
game.sets.forEach { set ->
set.cubes.forEach { (color, amount) ->
minCubesNeededByColor[color] = maxOf(minCubesNeededByColor[color]!!, amount)
}
}
return@sumOf minCubesNeededByColor.values.reduce(Int::times)
}
}
override val partOneTestExamples: Map<List<String>, Int> = mapOf(
listOf(
"Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green",
"Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue",
"Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red",
"Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red",
"Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green"
) to 8
)
override val partTwoTestExamples: Map<List<String>, Int> = mapOf(
listOf(
"Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green",
"Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue",
"Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red",
"Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red",
"Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green"
) to 2286
)
}
| 0 |
Kotlin
| 0 | 1 |
398fb9873cceecb2496c79c7adf792bb41ea85d7
| 3,301 |
advent-of-code-2023
|
MIT License
|
day-15/src/main/kotlin/Chiton.kt
|
diogomr
| 433,940,168 | false |
{"Kotlin": 92651}
|
import kotlin.system.measureTimeMillis
fun main() {
val partOneMillis = measureTimeMillis {
println("Part One Solution: ${partOne()}")
}
println("Part One Solved in: $partOneMillis ms")
val partTwoMillis = measureTimeMillis {
println("Part Two Solution: ${partTwo()}")
}
println("Part Two Solved in: $partTwoMillis ms")
}
typealias Point = Pair<Int, Int>
private fun partOne(): Int {
val map: Array<IntArray> = readInputLines()
.map { it.toCharArray().map { c -> c.digitToInt() }.toIntArray() }
.toTypedArray()
val distanceMap = dijkstraShortestDistance(Point(0, 0), map)
return distanceMap[map.size - 1][map.size - 1].first
}
fun dijkstraShortestDistance(start: Point, map: Array<IntArray>): Array<Array<Pair<Int, Boolean>>> {
val distance = Array(map.size) { Array(map.size) { Pair(Int.MAX_VALUE, false) } }
distance[start.first][start.second] = Pair(0, true)
var left = map.size * map.size
var cur = start
while (left-- > 0) {
distance[cur.first][cur.second] = distance[cur.first][cur.second].copy(second = true)
val adj = findAdjacent(cur, map)
for (i in adj.indices) {
val (x, y) = adj[i]
val newDistance = map[x][y] + distance[cur.first][cur.second].first
if (distance[x][y].first > newDistance) distance[x][y] = distance[x][y].copy(first = newDistance)
}
var value = Int.MAX_VALUE
for (i in distance.indices) {
for (j in distance.indices) {
if (!distance[i][j].second && distance[i][j].first < value) {
value = distance[i][j].first
cur = Point(i, j)
}
}
}
}
return distance
}
fun findAdjacent(point: Point, map: Array<IntArray>): List<Point> {
val range = map.indices
val (x, y) = point
return listOf(
Point(x, y - 1),
Point(x, y + 1),
Point(x - 1, y),
Point(x + 1, y),
)
.filter { (itx, ity) -> itx in range && ity in range }
}
private fun partTwo(): Int {
val map: Array<IntArray> = readInputLines()
.map { it.toCharArray().map { c -> c.digitToInt() }.toIntArray() }
.toTypedArray()
val mapExpanded = expandMap(map)
val distanceMap = dijkstraShortestDistance(Point(0, 0), mapExpanded)
return distanceMap[mapExpanded.size - 1][mapExpanded.size - 1].first
}
fun expandMap(map: Array<IntArray>): Array<IntArray> {
val size = map.size
val expandedMap = Array(size * 5) { IntArray(size * 5) }
for (i in 0..4) {
for (j in 0..4) {
addAndCopy(i * size, j * size, i + j, map, expandedMap)
}
}
return expandedMap
}
fun addAndCopy(x: Int, y: Int, add: Int, from: Array<IntArray>, to: Array<IntArray>) {
for (i in from.indices) {
for (j in from.indices) {
val new = from[i][j] + add
to[x + i][y + j] = if (new > 9) new - 9 else new
}
}
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 |
Kotlin
| 0 | 0 |
17af21b269739e04480cc2595f706254bc455008
| 3,214 |
aoc-2021
|
MIT License
|
src/main/kotlin/day15/Day15.kt
|
Avataw
| 572,709,044 | false |
{"Kotlin": 99761}
|
package day15
import kotlin.math.abs
fun solveA(input: List<String>, targetRow: Long): Int {
val sensors = input.parseSensors()
val beaconPositions = sensors.map { it.closestBeacon }.filter { it.y == targetRow }.toSet()
val noBeaconAtLeftest = sensors.mapNotNull { it.noBeaconsAt(targetRow)?.first }.min()
val noBeaconAtRightest = sensors.mapNotNull { it.noBeaconsAt(targetRow)?.second }.max()
val beaconsInRange = beaconPositions.filter { it.x in noBeaconAtLeftest..noBeaconAtRightest }
return (noBeaconAtLeftest..noBeaconAtRightest).count() - beaconsInRange.count()
}
fun solveB(input: List<String>, max: Long): Long? {
val sensors = input.parseSensors()
for (targetRow in 0..max) {
val ranges = sensors.mapNotNull { it.noBeaconsAt(targetRow) }.map { it.first..it.second }
ranges.forEach {
val leftBorder = it.first - 1
val rightBorder = it.last + 1
if (leftBorder >= 0 && ranges.all { range -> !range.contains(leftBorder) }) return leftBorder * 4000000 + targetRow
if (rightBorder <= max && ranges.all { range -> !range.contains(rightBorder) }) return rightBorder * 4000000 + targetRow
}
}
return null
}
fun List<String>.parseSensors() = this.map {
val beaconString = it.split(" at ").last()
val beacon = beaconString.toPosition()
val sensorString = it.drop(10).split(":").first()
Sensor(sensorString.toPosition(), beacon)
}
fun String.toPosition(): Position {
val input = this.split(", ")
val x = input.first().split("=").last().toLong()
val y = input.last().split("=").last().toLong()
return Position(x, y)
}
data class Position(val x: Long, val y: Long) {
fun distanceTo(other: Position) = abs(x - other.x) + abs(y - other.y)
}
data class Sensor(val position: Position, val closestBeacon: Position) {
private val maxDistance = position.distanceTo(closestBeacon)
fun noBeaconsAt(y: Long): Pair<Long, Long>? {
val start = Position(position.x, y)
val distanceToStart = position.distanceTo(start)
if (distanceToStart > maxDistance) return null
val diff = maxDistance - distanceToStart
return Pair(position.x - diff, position.x + diff)
}
}
| 0 |
Kotlin
| 2 | 0 |
769c4bf06ee5b9ad3220e92067d617f07519d2b7
| 2,263 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day14.kt
|
proggler23
| 573,129,757 | false |
{"Kotlin": 27990}
|
import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
return input.parse14().dropSand1()
}
fun part2(input: List<String>): Int {
return input.parse14().dropSand2()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
enum class Material {
AIR,
ROCK,
SAND
}
fun List<String>.parse14(): Cave {
val grid = Array(1000) { Array(500) { Material.AIR } }
for (line in this) {
line.split("->")
.map { coords -> coords.trim().split(",").let { (x, y) -> x.toInt() to y.toInt() } }
.zipWithNext().forEach { (coord1, coord2) ->
(min(coord1.first, coord2.first)..max(coord1.first, coord2.first)).forEach { x ->
(min(coord1.second, coord2.second)..max(coord1.second, coord2.second)).forEach { y ->
grid[x][y] = Material.ROCK
}
}
}
}
return Cave(grid)
}
data class Cave(val grid: Array<Array<Material>>) {
private val lowestRock =
grid.indices.flatMap { x -> grid[x].indices.filter { y -> grid[x][y] == Material.ROCK } }.max()
private fun dropSand(predicate: (Pair<Int, Int>) -> Boolean): Int {
for (i in 0..Int.MAX_VALUE) {
var sand = 500 to 0
while (sand.second <= lowestRock) {
val newSand = sand.move()
if (newSand == sand) break
else sand = newSand
}
if (predicate(sand)) return i
else grid[sand.first][sand.second] = Material.SAND
}
return -1
}
fun dropSand1() = dropSand { (_, y) -> y > lowestRock }
fun dropSand2() = dropSand { (x, y) -> grid[x][y] == Material.SAND }
private fun Pair<Int, Int>.move(): Pair<Int, Int> {
return when (Material.AIR) {
grid[first][second + 1] -> first to second + 1
grid[first - 1][second + 1] -> first - 1 to second + 1
grid[first + 1][second + 1] -> first + 1 to second + 1
else -> this
}
}
}
| 0 |
Kotlin
| 0 | 0 |
584fa4d73f8589bc17ef56c8e1864d64a23483c8
| 2,324 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day02.kt
|
aamielsan
| 572,653,361 | false |
{"Kotlin": 9363}
|
private fun String.splitToPair(): Pair<String, String> =
Pair(substringBefore(" "), substringAfter(" "))
enum class Hand(val score: Int) {
Rock(1),
Paper(2),
Scissor(3),
Unknown(0);
companion object {
fun fromString(string: String): Hand =
when (string) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissor
else -> Unknown
}
}
}
enum class Play(val hand: Hand, val wins: Hand, val loses: Hand) {
Rock(Hand.Rock, wins = Hand.Scissor, loses = Hand.Paper),
Paper(Hand.Paper, wins = Hand.Rock, loses = Hand.Scissor),
Scissor(Hand.Scissor, wins = Hand.Paper, loses = Hand.Rock),
Unknown(Hand.Unknown, wins = Hand.Unknown, loses = Hand.Unknown);
fun compare(other: Play): Result =
when (other.hand) {
wins -> Result.Win
loses -> Result.Lose
hand -> Result.Draw
else -> Result.Unknown
}
companion object {
fun fromString(string: String): Play =
fromHand(Hand.fromString(string))
fun fromHand(play: Hand): Play =
when (play) {
Hand.Rock -> Rock
Hand.Paper -> Paper
Hand.Scissor -> Scissor
Hand.Unknown -> Unknown
}
}
}
enum class Result(val score: Int) {
Win(6),
Lose(0),
Draw(3),
Unknown(0);
companion object {
fun fromString(string: String): Result =
when (string) {
"X" -> Lose
"Y" -> Draw
"Z" -> Win
else -> Unknown
}
}
}
fun main() {
fun part1(input: List<String>): Int =
input
.map(String::splitToPair)
.map { Pair(Play.fromString(it.first), Play.fromString(it.second)) }
.sumOf { (opponentPlay, myPlay) ->
val roundResult: Result = myPlay.compare(opponentPlay)
roundResult.score + myPlay.hand.score
}
fun part2(input: List<String>): Int =
input
.map(String::splitToPair)
.map { Pair(Play.fromString(it.first), Result.fromString(it.second)) }
.sumOf { (opponentPlay, expectedResult) ->
val myHand: Hand = when (expectedResult) {
Result.Draw -> opponentPlay.hand
Result.Win -> opponentPlay.loses
Result.Lose -> opponentPlay.wins
else -> opponentPlay.hand
}
myHand.score + expectedResult.score
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
9a522271bedb77496e572f5166c1884253cb635b
| 2,728 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
gcj/y2020/round2/c.kt
|
mikhail-dvorkin
| 93,438,157 | false |
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
|
package gcj.y2020.round2
private fun solve(): Int {
val n = readInt()
data class Point(val x: Int, val y: Int)
val points = List(n) { val (x, y) = readInts(); Point(x, y) }
val dirs = points.cartesianTriangle().map { (p, q) ->
val (x, y) = dividedByGcd(p.x - q.x, p.y - q.y)
if (x > 0 || (x == 0 && y > 0)) (x to y) else (-x to -y)
}.toSet()
return dirs.map { (x, y) ->
val sizes = points.groupBy { it.x.toLong() * y - it.y.toLong() * x }.map { it.value.size }
val bad = sizes.count { it == 1 } + sizes.filter { it > 1 }.sum() % 2
sizes.sum() - maxOf(bad - 2, 0)
}.maxOrNull() ?: 1
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun dividedByGcd(a: Int, b: Int) = gcd(a.abs(), b.abs()).let { a / it to b / it }
private tailrec fun gcd(a: Int, b: Int): Int = if (a == 0) b else gcd(b % a, a)
private fun Int.abs() = kotlin.math.abs(this)
private fun <T> Iterable<T>.cartesianTriangle() = withIndex().flatMap { x -> take(x.index).map { x.value to it } }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 |
Java
| 1 | 9 |
30953122834fcaee817fe21fb108a374946f8c7c
| 1,192 |
competitions
|
The Unlicense
|
src/Day12.kt
|
vjgarciag96
| 572,719,091 | false |
{"Kotlin": 44399}
|
import java.util.LinkedList
import java.util.Queue
fun main() {
data class Node(val x: Int, val y: Int)
fun buildGraph(input: List<String>): Map<Node, List<Node>> {
val rowLength = input.first().length
val adjacencyList = HashMap<Node, ArrayList<Node>>(rowLength * input.size)
val elevations = input.map { it.replace('S', 'a').replace('E', 'z') }
elevations.forEachIndexed { y, row ->
row.forEachIndexed { x, nodeValue ->
val adjacentNodes = ArrayList<Node>()
// left node
if (x > 0 && elevations[y][x - 1] <= nodeValue + 1) {
adjacentNodes.add(Node(x - 1, y))
}
// right node
if (x < row.length - 1 && elevations[y][x + 1] <= nodeValue + 1) {
adjacentNodes.add(Node(x + 1, y))
}
// top node
if (y > 0 && elevations[y - 1][x] <= nodeValue + 1) {
adjacentNodes.add(Node(x, y - 1))
}
// bottom node
if (y < elevations.size - 1 && elevations[y + 1][x] <= nodeValue + 1) {
adjacentNodes.add(Node(x, y + 1))
}
adjacencyList[Node(x, y)] = adjacentNodes
}
}
return adjacencyList
}
fun shortestPathLength(graph: Map<Node, List<Node>>, source: Node, destination: Node): Int? {
val distances = HashMap<Node, Int>(graph.size)
val visitedNodes = HashSet<Node>().apply { add(source) }
val searchQueue: Queue<Node> = LinkedList()
val sourceNeighbours = graph[source] ?: return null
searchQueue.addAll(sourceNeighbours)
sourceNeighbours.forEach { neighbour -> distances[neighbour] = 1 }
while (!searchQueue.isEmpty()) {
val currentNode: Node = searchQueue.poll()
if (currentNode in visitedNodes) continue
val adjacentNodes = graph[currentNode] ?: continue
if (destination in adjacentNodes) {
return distances.getValue(currentNode) + 1
} else {
adjacentNodes.forEach { newNode ->
distances[newNode] = distances.getValue(currentNode) + 1
searchQueue.add(newNode)
}
visitedNodes.add(currentNode)
}
}
return null
}
fun part1(input: List<String>): Int {
val startNode = Node(
x = input.first { it.contains('S') }.indexOfFirst { it == 'S' },
y = input.indexOfFirst { it.contains('S') },
)
val endNode = Node(
x = input.first { it.contains('E') }.indexOfFirst { it == 'E' },
y = input.indexOfFirst { it.contains('E') },
)
val graph = buildGraph(input)
return shortestPathLength(graph, startNode, endNode)
?: error("No path found between $startNode and $endNode")
}
fun part2(input: List<String>): Int {
val startNodes = ArrayList<Node>()
input.forEachIndexed { j, row ->
row.forEachIndexed { i, elevation ->
if (elevation == 'a' || elevation == 'S') {
startNodes.add(Node(i, j))
}
}
}
val endNode = Node(
x = input.first { it.contains('E') }.indexOfFirst { it == 'E' },
y = input.indexOfFirst { it.contains('E') },
)
val graph = buildGraph(input)
return startNodes.mapNotNull { startNode ->
shortestPathLength(graph, startNode, endNode)
}.min()
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
ee53877877b21166b8f7dc63c15cc929c8c20430
| 3,889 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day07.kt
|
hrach
| 572,585,537 | false |
{"Kotlin": 32838}
|
sealed interface Node {
val name: String
val size: Int
data class Dir(
override val name: String,
val nodes: MutableList<Node>,
val parent: Dir?,
) : Node {
override val size: Int
get() {
return nodes.sumOf { it.size }
}
val dirs: Sequence<Dir> = sequence {
yield(this@Dir)
yieldAll(nodes.filterIsInstance<Dir>().flatMap { it.dirs })
}
}
data class File(
override val name: String,
override val size: Int,
) : Node
}
fun parseInput(input: List<String>): Node.Dir {
val root = Node.Dir(nodes = mutableListOf(), name = "/", parent = null)
var wd = root
input.filter { it.isNotBlank() }.forEach { line ->
when {
line.startsWith("$ cd") -> {
wd = getDir(root, wd, line.removePrefix("$ cd ").trim())
}
line.startsWith("$ ls") -> {
// no-op
}
line.startsWith("dir ") -> {
getDir(root, wd, line.removePrefix("dir ").trim())
}
else -> {
val (size, name) = line.split(" ", limit = 2)
wd.nodes.add(Node.File(size = size.toInt(), name = name.trim()))
}
}
}
return root
}
fun getDir(root: Node.Dir, wd: Node.Dir, path: String): Node.Dir {
return when (path) {
"/" -> root
".." -> wd.parent!!
else -> {
if (wd.nodes.none { it is Node.Dir && it.name == path }) {
wd.nodes.add(
Node.Dir(nodes = mutableListOf(), name = path, parent = wd)
)
}
wd.nodes.filterIsInstance<Node.Dir>().first { it.name == path }
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val tree = parseInput(input)
return tree.dirs.filter { it.size <= 100000 }.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val tree = parseInput(input)
val needed = (tree.size - (70000000 - 30000000))
return tree.dirs.filter { it.size >= needed }.minOf { it.size }
}
val testInput = readInput("Day07_test")
check(part1(testInput), 95437)
check(part2(testInput), 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
40b341a527060c23ff44ebfe9a7e5443f76eadf3
| 2,394 |
aoc-2022
|
Apache License 2.0
|
src/day15/Day15.kt
|
spyroid
| 433,555,350 | false | null |
package day15
import com.github.ajalt.mordant.terminal.Terminal
import readInput
import java.util.*
import kotlin.system.measureTimeMillis
private fun solve(input: List<List<Int>>): Int {
val start = Point(0, 0)
val destination = Point(input.lastIndex, input.first().lastIndex)
val seen = mutableSetOf(start)
val queue = PriorityQueue<ContinuationPoint>(compareBy { it.risk }).also { it.add(ContinuationPoint(start, 0)) }
while (queue.peek().position != destination) {
val (position, risk) = queue.poll()
position.neighbours()
.filter { it.x in 0..destination.x && it.y in 0..destination.y }
.filterNot { seen.contains(it) }
.forEach { neighbour ->
(risk + input[neighbour.y][neighbour.x]).let { neighbourRisk ->
queue.add(ContinuationPoint(neighbour, neighbourRisk))
}
seen.add(neighbour)
}
}
return queue.poll().risk
}
private data class Point(val x: Int, val y: Int) {
fun neighbours() = setOf(Point(x - 1, y), Point(x + 1, y), Point(x, y + 1), Point(x, y - 1))
}
private data class ContinuationPoint(val position: Point, val risk: Int)
private fun expandInput(input: List<List<Int>>): List<List<Int>> {
val valueMapper = { value: Int -> if (value == 9) 1 else value + 1 }
val rows = input.map { generateSequence(it) { row -> row.map(valueMapper) }.take(5).toList().flatten() }
return generateSequence(rows) { chunk -> chunk.map { row -> row.map(valueMapper) } }.take(5).toList().flatten()
}
fun main() {
fun part1(input: List<String>): Int {
val data = input.map { line -> line.map { it.toString().toInt() } }
return solve(data)
}
fun part2(input: List<String>): Int {
val data = input.map { line -> line.map { it.toString().toInt() } }
return solve(expandInput(data))
}
val testData = readInput("day15/test")
val inputData = readInput("day15/input")
val term = Terminal()
var res1 = part1(testData)
check(res1 == 40) { "Expected 40 but got $res1" }
var time = measureTimeMillis { res1 = part1(inputData) }
term.success("⭐️ Part1: $res1 in $time ms")
time = measureTimeMillis { res1 = part2(inputData) }
term.success("⭐️ Part2: $res1 in $time ms")
}
| 0 |
Kotlin
| 0 | 0 |
939c77c47e6337138a277b5e6e883a7a3a92f5c7
| 2,340 |
Advent-of-Code-2021
|
Apache License 2.0
|
src/Day02.kt
|
GunnarBernsteinHH
| 737,845,880 | false |
{"Kotlin": 10952}
|
/*
* --- Day 2: Cube Conundrum ---
* Source: https://adventofcode.com/2023/day/2
*/
/** main function containing sub-functions like a class */
fun main() {
data class CubeSet(val red: Int, val green: Int, val blue: Int)
data class Game(val id: Int, val cubeSets: List<CubeSet>)
/** Parse input and return a list of class Game with their cube throws */
fun parse(input: List<String>) = input.map { line ->
// First Split String to separate Game and cube throws
// Game 1: 7 red, 14 blue; 2 blue, 3 red, 3 green; 4 green, 12 blue, 15 red; 3 green, 12 blue, 3 red; 11 red, 2 green
// interesting, one can split in destructive declaration
val (game, cubeSets) = line.split(":")
// use regex to get game id
val id = "Game (\\d+)".toRegex().find(game)!!.groupValues[1].toInt()
// use regex to get set cubes
// interesting part is the map function to create a list
cubeSets.split(";").map { cubeSet ->
val red = "(\\d+) red".toRegex().find(cubeSet)?.groupValues?.get(1)?.toInt() ?: 0
val green = "(\\d+) green".toRegex().find(cubeSet)?.groupValues?.get(1)?.toInt() ?: 0
val blue = "(\\d+) blue".toRegex().find(cubeSet)?.groupValues?.get(1)?.toInt() ?: 0
CubeSet(red, green, blue)
}.let {
Game(id, it)
}
}
/* Solution from <NAME>, Kotlin Advent of Code
* https://www.youtube.com/watch?v=CCr6yWMkiZU&list=PLlFc5cFwUnmzk0wvYW4aTl57F2VNkFisU&index=2 */
fun part1(input: List<String>): Int {
val maxRed = 12
val maxGreen = 13
val maxBlue = 14
val games = parse (input)
val sumOfGameIds = games.filter {
// filter games not possible with the number of cubes
it.cubeSets.none {
it.red > maxRed || it.green > maxGreen || it.blue > maxBlue
}
}.sumOf { it.id } // sum ids of the game as required result
return sumOfGameIds
}
fun part2(input: List<String>): Int {
val games = parse (input)
var result = 0
games.forEach {game ->
var redRequired = 0
var greenRequired = 0
var blueRequired = 0
game.cubeSets.forEach {
if (redRequired < it.red) redRequired = it.red
if (greenRequired < it.green) greenRequired = it.green
if (blueRequired < it.blue) blueRequired = it.blue
}
result += redRequired * greenRequired * blueRequired
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("input.day02.test1.txt")
check(part2(testInput) == 840)
val input = readInput("input.day02.txt")
println("Results for 2023, day 2:")
println("Result of part 1: " + part1(input))
println("Result of part 2: " + part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
bc66eef73bca2e64dfa5d83670266c8aaeae5b24
| 2,951 |
aoc-2023-in-kotlin
|
MIT License
|
algorithms/src/main/kotlin/com/kotlinground/algorithms/dynamicprogramming/mindistance/minDistance.kt
|
BrianLusina
| 113,182,832 | false |
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
|
package com.kotlinground.algorithms.dynamicprogramming.mindistance
/**
* Returns the minimum number of operations required to convert a string a into string b
*
* Edit distance is a classic DP problem. It is used to quantify the dissimilarity of two given strings by counting
* the minimum possible number of operations required to transform one string into the other.
*
*Given that the constraints, we assume that a O(m * n) solution would pass.
*
* Let's define dp[i][j] as the minimum edit distance between the first i character of word1 and the first j characters
* of word2. In example 1, dp[3][2] would be the edit distance between word1[1..3] (HOR) and word2[1..2](RO).
*
* If the last character is the same, then dp[i][j] would be dp[i - 1][j - 1] because we don't need to perform any
* operation. Otherwise, we need to perform either one. There are three possible ways to do the transformation.
*
* 1. We can transform word1[1..i] to word2[1..j-1] by adding word2[j] afterwards to get word2[1..j].
* 2. We can transform word1[1..i-1] to word2[1..j] by deleting word1[i].
* 3. We can transform word1[1..i-1] to word2[1..j-1] by exchanging the original word1[i] for word2[j].
*
* Therefore, the transition would be dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) if word1[i] is
* not equal to word2[j].
*
* What is the base case then? The base case is simply an edit distance between the empty string and non-empty string,
* i.e. dp[i][0] = i and dp[0][j] = j. The answer would be dp[m][n]. This algorithm is also known as Wagner–Fischer
* algorithm.
*
* Time Complexity: O(m*n)
* Space Complexity: O(m*n)
*/
fun minDistance(word1: String, word2: String): Int {
// strings are exactly the same, so no need for performing any operations on it
if (word1 == word2) {
return 0
}
// if string a is empty, then it will need the length of string b as the number of operations
if (word1.isEmpty()) {
return word2.length
}
val m = word1.length
val n = word2.length
val dp = Array(m + 1) { IntArray(n + 1) }
for (i in 0..m) {
for (j in 0..n) {
dp[i][j] = when {
i == 0 -> j
j == 0 -> i
word1[i - 1] == word2[j - 1] -> dp[i - 1][j - 1]
else -> 1 + minOf(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1])
}
}
}
return dp[m][n]
}
| 1 |
Kotlin
| 1 | 0 |
5e3e45b84176ea2d9eb36f4f625de89d8685e000
| 2,442 |
KotlinGround
|
MIT License
|
Advent-of-Code-2023/src/Day11.kt
|
Radnar9
| 726,180,837 | false |
{"Kotlin": 93593}
|
import kotlin.math.max
import kotlin.math.min
private const val AOC_DAY = "Day11"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
private const val EXPANDED_TWICE = 2
private const val EXPANDED_MILLION = 1_000_000
private data class Galaxy(val row: Int, val col: Int)
/**
* Finds the shortest path between every different pair of galaxies and sums them up.
* In case of empty rows or columns, the path is expanded by the given [expansion] factor.
*/
private fun calculateSumOfPaths(grid: List<String>, expansion: Int): Long {
val emptyRows = grid.indices.filter { y -> grid[0].indices.all { x -> grid[y][x] == '.' } }.toSet()
val emptyCols = grid[0].indices.filter { x -> grid.indices.all { y -> grid[y][x] == '.' } }.toSet()
val galaxies = buildList {
for (row in grid.indices) {
for (col in grid[row].indices) {
if (grid[row][col] == '#') add(Galaxy(row, col))
}
}
}
var sum = 0L
for (i in galaxies.indices) {
val galaxy1 = galaxies[i]
for (j in i + 1..<galaxies.size) {
val galaxy2 = galaxies[j]
for (row in min(galaxy1.row, galaxy2.row)..<max(galaxy1.row, galaxy2.row)) {
sum += if (row in emptyRows) expansion else 1
}
for (col in min(galaxy1.col, galaxy2.col)..<max(galaxy1.col, galaxy2.col)) {
sum += if (col in emptyCols) expansion else 1
}
}
}
return sum
}
private fun part1(input: List<String>): Long {
return calculateSumOfPaths(input, EXPANDED_TWICE)
}
private fun part2(input: List<String>): Long {
return calculateSumOfPaths(input, EXPANDED_MILLION)
}
fun main() {
createTestFiles(AOC_DAY)
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 374
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 82000210
println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 10276166" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 598693078798" else ""}")
}
| 0 |
Kotlin
| 0 | 0 |
e6b1caa25bcab4cb5eded12c35231c7c795c5506
| 2,344 |
Advent-of-Code-2023
|
Apache License 2.0
|
y2023/src/main/kotlin/adventofcode/y2023/Day13.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2023
import adventofcode.io.AdventSolution
import adventofcode.util.algorithm.transposeString
fun main() {
Day13.solve()
}
object Day13 : AdventSolution(2023, 13, "Point of Incidence") {
override fun solvePartOne(input: String) = solve(input, String::equals)
override fun solvePartTwo(input: String) = solve(input) { l, r ->
l.zip(r).count { (a, b) -> a != b } == 1
}
}
private fun solve(input: String, reflectionTest: (left: String, right: String) -> Boolean): Int {
val patterns = parse(input)
val cols = patterns.sumOf { indexOfMirror(it, reflectionTest) }
val rows = patterns.sumOf { indexOfMirror(it.transposeString(), reflectionTest) }
return 100 * cols + rows
}
private fun parse(input: String) = input.split("\n\n").map { it.lines() }
private fun indexOfMirror(lines: List<String>, reflectionTest: (left: String, right: String) -> Boolean) =
generateSequence<Pair<List<String>, List<String>>>(Pair(emptyList(), lines)) { (left, right) ->
Pair(left + right.first(), right.drop(1))
}
.drop(1).takeWhile { it.second.isNotEmpty() }
.map { (l, r) -> Pair(l.asReversed().joinToString(""), r.joinToString("")) }
.indexOfFirst { (l, r) -> reflectionTest(l.take(r.length), r.take(l.length)) } + 1
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 1,308 |
advent-of-code
|
MIT License
|
src/Day05.kt
|
rxptr
| 572,717,765 | false |
{"Kotlin": 9737}
|
data class Instruction(val quantity: Int, val from: Int, val to: Int)
fun main() {
fun parsInstructions(input: String): List<Instruction> = input.lines().filter(String::isNotBlank).map { line ->
val (a, b, c) = Regex("move (\\d+) from (\\d+) to (\\d+)").find(line)!!.destructured
Instruction(a.toInt(), b.toInt() - 1, c.toInt() - 1)
}
fun parsDrawing(input: String): List<String> =
input.lines().reversed().drop(1).fold(mutableListOf()) { acc, line ->
line.windowed(4, 4, true).foldIndexed(acc) { i, stacks, window ->
Regex("[([A-Z]1)]").find(window)?.value?.let {
if (stacks.isEmpty() || stacks.size <= i) stacks.add(it) else stacks[i] = stacks[i] + it
}
stacks
}
}
fun parsInput(input: String): Pair<List<Instruction>, List<String>> =
input.split("\n\n").let { (drawing, moves) ->
Pair(parsInstructions(moves), parsDrawing(drawing))
}
fun move(stacks: List<String>, instruction: Instruction, bulk: Boolean = false): List<String> {
val newState = stacks.toMutableList()
val popped = newState[instruction.from].takeLast(instruction.quantity)
newState[instruction.from] = newState[instruction.from].dropLast(instruction.quantity)
newState[instruction.to] = newState[instruction.to] + if (bulk) popped else popped.reversed()
return newState
}
fun part1(input: String): String {
val (instructions, stacks) = parsInput(input)
return instructions.fold(stacks) { state, ins -> move(state, ins) }
.reduce { acc, i -> acc + i.last() }
}
fun part2(input: String): String {
val (instructions, stacks) = parsInput(input)
return instructions.fold(stacks) { state, ins -> move(state, ins, true) }
.reduce { acc, i -> acc + i.last() }
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
989ae08dd20e1018ef7fe5bf121008fa1c708f09
| 2,127 |
aoc2022
|
Apache License 2.0
|
src/Day03.kt
|
pmellaaho
| 573,136,030 | false |
{"Kotlin": 22024}
|
fun main() {
/**
* 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.
*/
fun Char.priority(): Int {
return when (this) {
in 'a'..'z' -> code - 96
in 'A'..'Z' -> code - 38
else -> 0
}
}
fun splitIntoCompartments(rucksack: String): Pair<String, String> {
val list = rucksack.chunked(rucksack.length / 2)
return Pair(list.first(), list.last())
}
fun part1(input: List<String>): Int {
var result = 0
input.forEach { rucksack ->
val (a, b) = splitIntoCompartments(rucksack)
a.firstOrNull { item ->
val match = b.firstOrNull { it == item }
result += match?.priority() ?: 0
match != null
}
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
val listOfGroups = input.chunked(3)
listOfGroups.forEach { group ->
group[0].firstOrNull { item ->
val match = group[1].firstOrNull { it == item }
var allMatch: Char? = null
if (match != null) {
allMatch = group[2].firstOrNull { match == it }
result += allMatch?.priority() ?: 0
}
allMatch != null
}
}
return result
}
fun part2v2(input: List<String>): Int {
val listOfGroups = input.chunked(3)
return listOfGroups.map {
val (a, b, c) = it
val common = a.toSet() intersect b.toSet() intersect c.toSet()
common.single()
}.sumOf { it.priority() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
// val res = part1(testInput)
// check(res == 157)
val res = part2v2(testInput)
check(res == 70)
// val input = readInput("Day03")
// println(part1(input))
// println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
cd13824d9bbae3b9debee1a59d05a3ab66565727
| 2,041 |
AoC_22
|
Apache License 2.0
|
src/main/kotlin/aoc2022/Day18.kt
|
j4velin
| 572,870,735 | false |
{"Kotlin": 285016, "Python": 1446}
|
package aoc2022
import readInput
private data class Point3(val x: Int, val y: Int, val z: Int) {
companion object {
fun fromString(input: String): Point3 {
val split = input.split(",").map { it.toInt() }
return Point3(split[0], split[1], split[2])
}
}
val neighbours by lazy {
buildSet {
add(Point3(x - 1, y, z))
add(Point3(x + 1, y, z))
add(Point3(x, y - 1, z))
add(Point3(x, y + 1, z))
add(Point3(x, y, z - 1))
add(Point3(x, y, z + 1))
}
}
fun getExposedSides(points: Collection<Point3>) = 6 - neighbours.count { points.contains(it) }
fun getExteriorSurfaceSides(isOutSide: (Point3) -> Boolean) = neighbours.count { isOutSide(it) }
}
private data class LavaDroplet(private val shapePoints: Collection<Point3>) {
val surfaceArea by lazy { shapePoints.sumOf { it.getExposedSides(shapePoints) } }
val exteriorSurfaceArea by lazy {
val max = Point3(shapePoints.maxOf { it.x }, shapePoints.maxOf { it.y }, shapePoints.maxOf { it.z })
val rangeX = 0..max.x
val rangeY = 0..max.y
val rangeZ = 0..max.z
val outsideCubes = mutableSetOf<Point3>()
val isOutside: (Point3) -> Boolean =
{ p -> outsideCubes.contains(p) || !rangeX.contains(p.x) || !rangeY.contains(p.y) || !rangeZ.contains(p.z) }
for (x in max.x downTo 0) {
for (y in max.y downTo 0) {
for (z in max.z downTo 0) {
val point = Point3(x, y, z)
if (!shapePoints.contains(point)) {
// empty (inside or outside)
val uncheckedNeighbours = point.neighbours.filter { !shapePoints.contains(it) }.toMutableSet()
val emptyConnectedPoints = mutableSetOf(point)
while (uncheckedNeighbours.isNotEmpty()) {
val n = uncheckedNeighbours.random()
uncheckedNeighbours.remove(n)
if (isOutside(n)) {
outsideCubes.addAll(emptyConnectedPoints)
break
} else {
emptyConnectedPoints.add(n)
uncheckedNeighbours.addAll(n.neighbours.filter { !shapePoints.contains(it) }
.filter { !uncheckedNeighbours.contains(it) && !emptyConnectedPoints.contains(it) })
}
}
}
}
}
}
shapePoints.sumOf { it.getExteriorSurfaceSides(isOutside) }
}
}
private fun part1(input: List<String>): Int {
val droplet = LavaDroplet(input.map { Point3.fromString(it) })
return droplet.surfaceArea
}
private fun part2(input: List<String>): Int {
val droplet = LavaDroplet(input.map { Point3.fromString(it) })
return droplet.exteriorSurfaceArea
}
fun main() {
val testInput = readInput("Day18_test", 2022)
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18", 2022)
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
f67b4d11ef6a02cba5b206aba340df1e9631b42b
| 3,284 |
adventOfCode
|
Apache License 2.0
|
src/Day09.kt
|
qmchenry
| 572,682,663 | false |
{"Kotlin": 22260}
|
fun main() {
data class Coordinate(val x: Int, val y: Int) {
operator fun plus(other: Coordinate): Coordinate {
return Coordinate(x + other.x, y + other.y)
}
operator fun minus(other: Coordinate): Coordinate {
return Coordinate(x - other.x, y - other.y)
}
operator fun times(multiplier: Int): Coordinate {
return Coordinate(x * multiplier, y * multiplier)
}
override operator fun equals(other: Any?): Boolean {
return other is Coordinate && other.x == x && other.y == y
}
}
data class Step(val direction: String, val distance: Int) {
val coordinate: Coordinate
get() = when (direction) {
"U" -> Coordinate(0, 1)
"D" -> Coordinate(0, -1)
"L" -> Coordinate(-1, 0)
"R" -> Coordinate(1, 0)
else -> throw IllegalArgumentException("Unknown direction: $direction")
}
fun coordinates(from: Coordinate): List<Coordinate> {
return (1..distance)
.map { from + coordinate * it }
}
constructor(string: String) : this(string.substring(0, 1), string.substring(2).toInt())
}
fun path(input: List<String>): List<Coordinate> {
var current = Coordinate(0, 0)
return listOf(current) + input.map { Step(it) }
.flatMap {
val coordinates = it.coordinates(current)
current = coordinates.last()
coordinates
}
}
fun followDelta(head: Coordinate, tail: Coordinate): Coordinate {
val diff = tail - head
return when {
diff.x == 2 -> Coordinate(head.x + 1, head.y)
diff.x == -2 -> Coordinate(head.x - 1, head.y)
diff.y == 2 -> Coordinate(head.x, head.y + 1)
diff.y == -2 -> Coordinate(head.x, head.y - 1)
else -> tail
}
}
fun follow(input: List<Coordinate>): List<Coordinate> {
val head = input.first()
var current = head
return input.map {
val next = followDelta(it, current)
current = next
current
}
}
fun part1(input: List<String>): Int {
val head = path(input)
val tail = follow(head)
return tail.distinct().size
}
fun part2(input: List<String>): Int {
val head = path(input)
var current = head
(1..9).forEach {
val next = follow(current)
current = next
}
println(current.forEach(::println))
println(current.distinct().size)
return current.distinct().size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_sample")
check(part1(testInput) == 13)
val testInput2 = readInput("Day09_sample2")
check(part2(testInput2) == 36)
val realInput = readInput("Day09_input")
println("Part 1: ${part1(realInput)}")
println("Part 2: ${part2(testInput)}")
}
| 0 |
Kotlin
| 0 | 0 |
2813db929801bcb117445d8c72398e4424706241
| 3,087 |
aoc-kotlin-2022
|
Apache License 2.0
|
src/main/kotlin/be/inniger/euler/problems11to20/Problem11.kt
|
bram-inniger
| 135,620,989 | false |
{"Kotlin": 20003}
|
package be.inniger.euler.problems11to20
private const val NR_ADJACENT = 4
/**
* Largest product in a grid
*
* In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
* The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
* What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
*/
fun solve11() =
if (doesGridFailValidation()) throw IllegalArgumentException("Grid needs to be rectangular!") // Verify if the grid is indeed a grid
else grid.indices // 0 until 20, y-coordinate
.flatMap { y ->
grid[0].indices // 0 until 20, x-coordinate
.map { x -> Coordinate(x, y) } // Put x and y together in a coordinate
} // This is now a List<Coordinate> containing all possible grid positions
.flatMap { coordinate ->
Direction.values() // Per coordinate, look in all (de-duplicated) directions (e.g. if you look down you don't need to look up)
.map { direction ->
Line(coordinate, direction)
} // Draw a line from a coordinate in a directions (line = 4 adjacent numbers)
} // This is now a List<Line> containing all possible lines that can be drawn from all possible grid positions
.filter(Line::isValid) // Only keep lines that fit inside the grid (e.g. if the origin is on the final row it does not make sense to have a line downwards)
.map(Line::product) // Of all valid lines calculate the product of the adjacent numbers
.max()!! // Get the greatest product
private val grid = Thread.currentThread().contextClassLoader.getResourceAsStream("Problem11.txt")
.reader()
.readLines() // Results in List<String>, 1 String per line in the file
.filter(String::isNotBlank) // Ignore blank lines
.map { it.split(" ") } // Results in List<List<String>>, split every line in its separate String values
.map { it.map(String::toInt) } // Results in List<List<Int>>, the grid, by converting every single String into an Int
private fun doesGridFailValidation() = grid
.map { it.size } // For the grid to be a rectangle, every row needs to have the same length
.distinct() // Get all the different row lengths in the grid
.count() != 1 // If there is more than 1 different length, the grid is not rectangular, and thus not a valid grid
private enum class Direction(internal val deltaX: Int, internal val deltaY: Int) {
DOWNWARD(0, 1),
RIGHTWARD(1, 0),
UP_RIGHT(1, -1),
DOWN_RIGHT(1, 1)
}
private data class Coordinate(internal val x: Int, internal val y: Int)
private data class Line(private val origin: Coordinate, private val direction: Direction) {
// Start from the coordinate, and walk in a Direction, to get 4 adjacent coordinates
private val line = (0 until NR_ADJACENT).map {
Coordinate(
origin.x + it * direction.deltaX,
origin.y + it * direction.deltaY
)
}
// A line will be inside the rectangle if both ends of the line are inside
internal val isValid = line.first().x in 0..grid[0].lastIndex &&
line.first().y in 0..grid.lastIndex &&
line.last().x in 0..grid[0].lastIndex &&
line.last().y in 0..grid.lastIndex
// Calculate the product of the 4 adjacent numbers on the line
internal val product
get() = line.map { grid[it.y][it.x] }
.reduce { acc, factor -> acc * factor }
}
| 0 |
Kotlin
| 0 | 0 |
8fea594f1b5081a824d829d795ae53ef5531088c
| 3,518 |
euler-kotlin
|
MIT License
|
aoc-2021/src/main/kotlin/nerok/aoc/aoc2021/day03/Day03.kt
|
nerok
| 572,862,875 | false |
{"Kotlin": 113337}
|
package nerok.aoc.aoc2021.day03
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun getMajority(input: List<List<Int>>, index: Int): Int {
return input.map { it[index] }.let {
if (it.sum()*2 == it.size) {
1
}
else if (it.sum() == 2 && it.size == 3) {
1
}
else if (it.sum() > it.size / 2) 1 else 0
}
}
fun higherReduction(set: List<List<Int>>): List<Int> {
var reductionSet = set
var index = 1
while (reductionSet.size > 1) {
val majority = getMajority(reductionSet, index)
reductionSet = reductionSet.filter { it[index] == majority }
index += 1
}
return reductionSet.first()
}
fun smallerReduction(set: List<List<Int>>): List<Int> {
var reductionSet = set
var index = 1
while (reductionSet.size > 1) {
val majority = getMajority(reductionSet, index)
reductionSet = reductionSet.filter { it[index] != majority }
index += 1
}
return reductionSet.first()
}
fun part1(input: List<String>): Long {
val countArray = IntArray(input.first().length) { 0 }
val inverseMask = IntArray(input.first().length) { 1 }.reduce { acc, i -> (acc shl 1) + i }
input
.map { it
.mapIndexed { index, value ->
if (value == '1') {
countArray[index] = (countArray[index] + 1)
}
else {
countArray[index] = (countArray[index] - 1)
}
}
}
val gamma = countArray
.map { if (it > 0) 1 else 0 }
.reduce { acc, i -> (acc shl 1) + i }
val epsilon = gamma.xor(inverseMask)
return (gamma*epsilon).toLong()
}
fun part2(inputValues: List<String>): Long {
val input = inputValues
.map { line ->
line.split("")
.filter {
it.isNotEmpty()
}
.map { it.toInt() }
}
val majority = getMajority(input, 0)
val highset = input.filter { it[0] == majority }
val lowset = input.filter { it[0] != majority }
val oxygenRating = higherReduction(highset)
val CO2Rating = smallerReduction(lowset)
val oxygenRatingDecimal = Integer.parseInt(oxygenRating.joinToString(separator = "") { it.toString() }, 2)
val CO2RatingDecimal = Integer.parseInt(CO2Rating.joinToString(separator = "") { it.toString() }, 2)
println(oxygenRatingDecimal)
println(CO2RatingDecimal)
println("${oxygenRatingDecimal*CO2RatingDecimal}")
return (oxygenRatingDecimal*CO2RatingDecimal).toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day03_test")
check(part1(testInput) == 198L)
check(part2(testInput) == 230L)
val input = Input.readInput("Day03")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
| 0 |
Kotlin
| 0 | 0 |
7553c28ac9053a70706c6af98b954fbdda6fb5d2
| 3,360 |
AOC
|
Apache License 2.0
|
src/year2021/Day5.kt
|
drademacher
| 725,945,859 | false |
{"Kotlin": 76037}
|
package year2021
import readFile
import java.awt.Point
private const val COORDINATE_SIZE = 1000
fun main() {
val input = parseInput(readFile("2021", "day5"))
val testInput = parseInput(readFile("2021", "day5_test"))
println(part1(testInput))
check(part1(testInput) == 5)
println("Part 1:" + part1(input))
check(part2(testInput) == 12)
println("Part 2:" + part2(input))
}
private fun parseInput(file: String): List<Line> {
return file
.replace(" -> ", ",")
.split("\n")
.filter { it != "" }
.map { it.split(",").map { it.toInt() } }
.map { Line(Point(it[0], it[1]), Point(it[2], it[3])) }
}
private fun part1(lines: List<Line>): Int {
val coords = Array(COORDINATE_SIZE) { IntArray(COORDINATE_SIZE) { 0 } }
lines
.filter { it.isHorizontalOrVertical }
.flatMap { it.points }
.forEach { point -> coords[point.y][point.x] += 1 }
return coords.sumOf { col -> col.filter { it >= 2 }.size }
}
private fun part2(lines: List<Line>): Int {
val coords = Array(COORDINATE_SIZE) { IntArray(COORDINATE_SIZE) { 0 } }
lines
.flatMap { it.points }
.forEach { point -> coords[point.y][point.x] += 1 }
return coords.sumOf { col -> col.filter { it >= 2 }.size }
}
class Line(private val start: Point, private val end: Point) {
val isHorizontalOrVertical: Boolean = start.x == end.x || start.y == end.y
val points: List<Point>
get() {
val xs =
if (start.x < end.x) {
(start.x..end.x)
} else {
(start.x downTo end.x)
}
val ys =
if (start.y < end.y) {
(start.y..end.y)
} else {
(start.y downTo end.y)
}
if (start.x == end.x) {
return ys.map { Point(start.x, it) }
}
if (start.y == end.y) {
return xs.map { Point(it, start.y) }
}
return xs.zip(ys).map { Point(it.first, it.second) }
}
}
| 0 |
Kotlin
| 0 | 0 |
4c4cbf677d97cfe96264b922af6ae332b9044ba8
| 2,131 |
advent_of_code
|
MIT License
|
kotlin/src/test/kotlin/nl/dirkgroot/adventofcode/year2023/Day23Test.kt
|
dirkgroot
| 724,049,902 | false |
{"Kotlin": 203339, "Rust": 123129, "Clojure": 78288}
|
package nl.dirkgroot.adventofcode.year2023
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
import java.util.*
private fun solution1(input: String) = solution(parse(input, false))
private fun solution2(input: String) = solution(parse(input, true))
private fun solution(map: Array<CharArray>): Int {
val edges = findEdges(map, Vertex(0, 1), Vertex(0, 1))
return longestPath(edges, Vertex(0, 1), Vertex(map.lastIndex, map[0].lastIndex - 1))
}
private fun findEdges(
map: Array<CharArray>,
prevVertex: Vertex,
startFrom: Vertex,
edges: MutableSet<Edge> = mutableSetOf(),
vertices: MutableSet<Vertex> = mutableSetOf(),
): MutableSet<Edge> {
var prev = prevVertex
var cur = startFrom
var n: List<Vertex>
var cost = if (prevVertex == startFrom) 0 else 1
var hasSlope = false
while (true) {
hasSlope = hasSlope || (map[cur.y][cur.x] in setOf('<', '>', '^', 'v'))
n = neighbors(map, cur).filterNot { it == prev }
if (n.isEmpty()) {
edges.add(Edge(prevVertex, cur, cost))
if (!hasSlope)
edges.add(Edge(cur, prevVertex, cost))
vertices.add(cur)
return edges
}
if (n.size > 1) break
cost++
prev = cur
cur = n[0]
}
edges.add(Edge(prevVertex, cur, cost))
if (!hasSlope)
edges.add(Edge(cur, prevVertex, cost))
if (vertices.contains(cur)) return edges
vertices.add(cur)
n.forEach { findEdges(map, cur, it, edges, vertices) }
return edges
}
private fun parse(input: String, ignoreSlopes: Boolean) =
input.lines().map {
if (ignoreSlopes)
it.map { c -> if (c == '.' || c == '#') c else '.' }.toCharArray()
else
it.toCharArray()
}.toTypedArray()
private fun longestPath(edges: MutableSet<Edge>, from: Vertex, to: Vertex): Int {
data class Candidate(val vertex: Vertex, val cost: Int, val prev: Candidate? = null) {
fun vertices() = generateSequence(this) { it.prev }
.map { it.vertex }
.toSet()
}
var optimum = 0
var bound = 0
val queue = PriorityQueue<Candidate> { a, b -> b.cost.compareTo(a.cost) }
queue.add(Candidate(from, 0))
while (queue.isNotEmpty()) {
val candidate = queue.poll()
if (candidate.vertex == to && candidate.cost > bound) {
optimum = candidate.cost
bound = candidate.cost
} else {
val vertices = candidate.vertices()
edges.filter { it.v1 == candidate.vertex && !vertices.contains(it.v2) }
.forEach { edge ->
val totalEdgeCost = candidate.cost + edge.cost
val upperBound = totalEdgeCost + edges
.filterNot { vertices.contains(it.v1) || vertices.contains(it.v2) }
.sumOf { it.cost }
if (upperBound >= bound) {
queue.add(Candidate(edge.v2, totalEdgeCost, candidate))
}
}
}
}
return optimum
}
private fun neighbors(map: Array<CharArray>, vertex: Vertex): List<Vertex> {
val result = mutableListOf<Vertex>()
if (vertex.y > 0 && (map[vertex.y - 1][vertex.x] == '.' || map[vertex.y - 1][vertex.x] == '^')) {
result.add(Vertex(vertex.y - 1, vertex.x))
}
if (vertex.x < map[0].lastIndex && (map[vertex.y][vertex.x + 1] == '.' || map[vertex.y][vertex.x + 1] == '>')) {
result.add(Vertex(vertex.y, vertex.x + 1))
}
if (vertex.y < map.lastIndex && (map[vertex.y + 1][vertex.x] == '.' || map[vertex.y + 1][vertex.x] == 'v')) {
result.add(Vertex(vertex.y + 1, vertex.x))
}
if (vertex.x > 0 && (map[vertex.y][vertex.x - 1] == '.' || map[vertex.y][vertex.x - 1] == '<')) {
result.add(Vertex(vertex.y, vertex.x - 1))
}
return result
}
private data class Edge(val v1: Vertex, val v2: Vertex, val cost: Int, var block: Boolean = false)
private data class Vertex(val y: Int, val x: Int)
//===============================================================================================\\
private const val YEAR = 2023
private const val DAY = 23
class Day23Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 94 }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 2246 }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 154 }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 6622 }
})
private val exampleInput =
"""
#.#####################
#.......#########...###
#######.#########.#.###
###.....#.>.>.###.#.###
###v#####.#v#.###.#.###
###.>...#.#.#.....#...#
###v###.#.#.#########.#
###...#.#.#.......#...#
#####.#.#.#######.#.###
#.....#.#.#.......#...#
#.#####.#.#.#########v#
#.#...#...#...###...>.#
#.#.#v#######v###.###v#
#...#.>.#...>.>.#.###.#
#####v#.#.###v#.#.###.#
#.....#...#...#.#.#...#
#.#########.###.#.#.###
#...###...#...#...#.###
###.###.#.###v#####v###
#...#...#.#.>.>.#.>.###
#.###.###.#.###.#.#v###
#.....###...###...#...#
#####################.#
""".trimIndent()
| 1 |
Kotlin
| 0 | 0 |
ced913cd74378a856813973a45dd10fdd3570011
| 5,475 |
adventofcode
|
MIT License
|
src/Day07.kt
|
haraldsperre
| 572,671,018 | false |
{"Kotlin": 17302}
|
abstract class FilesystemEntity(val name: String, val parent: Directory? = null, var size: Long = 0L)
class Directory(name: String, parent: Directory? = null) : FilesystemEntity(name, parent) {
private val children = mutableListOf<FilesystemEntity>()
fun add(entity: FilesystemEntity) {
children.add(entity)
}
fun getChildren() = children.toList()
fun getChild(name: String) = children.find { it.name == name }
}
class File(name: String, parent: Directory, size: Long) : FilesystemEntity(name, parent, size)
fun getEntityFromLine(line: String, currentDir: Directory): FilesystemEntity {
val (info, name) = line.split(" ")
return try {
File(name, currentDir, info.toLong())
} catch (e: NumberFormatException) {
Directory(name, currentDir)
}
}
fun buildFilesystemTree(input: List<String>): Directory {
val root = Directory("/")
var currentDir = root
for (line in input) {
if (line == "$ ls") {
continue
} else if (line.startsWith("$ cd")) {
val name = line.removePrefix("$ cd ")
currentDir = when (name) {
".." -> currentDir.parent ?: currentDir
"/" -> root
else -> currentDir.getChild(name) as Directory
}
} else {
val entity = getEntityFromLine(line, currentDir)
if (currentDir.getChild(entity.name) == null) currentDir.add(entity)
}
}
return root
}
fun getTopologicalOrdering(root: Directory): List<FilesystemEntity> {
val sorted = mutableListOf<FilesystemEntity>()
val visited = mutableSetOf<FilesystemEntity>()
fun dfs(entity: FilesystemEntity) {
if (entity in visited) return
visited.add(entity)
if (entity is Directory) {
entity.getChildren().forEach { dfs(it) }
}
sorted.add(entity)
}
dfs(root)
return sorted
}
fun getDirectoriesWithTotalSize(input: List<String>): List<Directory> {
val root = buildFilesystemTree(input)
val sorted = getTopologicalOrdering(root)
for (entity in sorted) {
entity.parent?.size = entity.parent?.size?.plus(entity.size) ?: 0L
}
return sorted.filterIsInstance<Directory>()
}
fun main() {
fun part1(input: List<Directory>): Long {
return input
.sumOf { directory ->
if (directory.size <= 100000L) directory.size else 0L
}
}
fun part2(input: List<Directory>): Long {
val totalSpace = 70000000L
val availableSpace = totalSpace - input.find { it.name == "/" }!!.size
val neededSpace = 30000000L - availableSpace
return input
.filter { it.size > neededSpace }
.minOf { it.size }
}
// test if implementation meets criteria from the description, like:
val testInput = getDirectoriesWithTotalSize(readInput("Day07_test"))
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = getDirectoriesWithTotalSize(readInput("Day07"))
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
c4224fd73a52a2c9b218556c169c129cf21ea415
| 3,123 |
advent-of-code-2022
|
Apache License 2.0
|
src/com/kingsleyadio/adventofcode/y2023/Day19.kt
|
kingsleyadio
| 435,430,807 | false |
{"Kotlin": 134666, "JavaScript": 5423}
|
package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val (workflows, ratings) = buildModel()
part1(workflows, ratings)
part2(workflows)
}
private fun part1(workflows: Map<String, Workflow>, ratings: List<PartRating>) {
val result = ratings.filter { rating ->
var result: WorkflowResult = WorkflowResult.Next("in")
while (result is WorkflowResult.Next) result = workflows.getValue(result.workflow).evaluate(rating)
result is WorkflowResult.Accepted
}.sumOf(PartRating::score)
println(result)
}
private fun part2(workflows: Map<String, Workflow>) {
var sum = 0L
val queue = ArrayDeque<Pair<String, Map<String, IntRange>>>()
queue.addLast("in" to mapOf("x" to 1..4000, "m" to 1..4000, "a" to 1..4000, "s" to 1..4000))
while (queue.isNotEmpty()) {
val (name, ranges) = queue.removeFirst()
var current = ranges
val workflow = workflows.getValue(name)
for (condition in workflow.conditions) {
if (condition.rating in current) {
val currentRange = current.getValue(condition.rating)
val conditionRange = condition.range
val intersection = currentRange.intersect(conditionRange)
val accepted = current + Pair(condition.rating, intersection)
when (condition.result) {
is WorkflowResult.Accepted -> sum += accepted.values.fold(1L) { acc, n -> acc * n.size }
is WorkflowResult.Next -> queue.addLast(condition.result.workflow to accepted)
else -> {}
}
val leftover = when (intersection.last) {
currentRange.last -> currentRange.first..<intersection.first
else -> intersection.last + 1..currentRange.last
}
current = current + Pair(condition.rating, leftover)
} else when (condition.result) {
is WorkflowResult.Accepted -> sum += current.values.fold(1L) { acc, n -> acc * n.size }
is WorkflowResult.Next -> queue.addLast(condition.result.workflow to current)
else -> {}
}
}
}
println(sum)
}
private fun buildModel(isSample: Boolean = false): Pair<Map<String, Workflow>, List<PartRating>> {
readInput(2023, 19, isSample).useLines { sequence ->
val lines = sequence.iterator()
val workflows = buildMap {
while (true) {
val line = lines.next()
val workflow = if (line.isNotEmpty()) line.toWorkflow() else break
put(workflow.name, workflow)
}
}
val ratings = buildList {
while (lines.hasNext()) add(lines.next().toPartRating())
}
return workflows to ratings
}
}
private fun String.toWorkflow(): Workflow {
val name = substringBefore('{')
val conditionRegex = "([xmas])([><])(\\d+):(\\w+)".toRegex()
val conditions = substringAfter('{').dropLast(1).split(",").map { c ->
val match = conditionRegex.matchEntire(c)
val (part, condition, value, next) = match?.groupValues?.drop(1) ?: listOf("", "", "", c)
val range = when (condition) {
">" -> value.toInt() + 1..4000
"<" -> 1..<value.toInt()
else -> 1..4000
}
val result = when (next) {
"A" -> WorkflowResult.Accepted
"R" -> WorkflowResult.Rejected
else -> WorkflowResult.Next(next)
}
Workflow.Condition(part, range, result)
}
return Workflow(name, conditions)
}
private fun String.toPartRating(): PartRating {
val ratings = substring(1, lastIndex).split(",").associate {
val (k, v) = it.split("=")
k to v.toInt()
}
return PartRating(ratings)
}
private class PartRating(val values: Map<String, Int>) {
val score get() = values.values.sum()
}
private class Workflow(val name: String, val conditions: List<Condition>) {
fun evaluate(rating: PartRating): WorkflowResult {
return conditions.firstNotNullOf { condition ->
val partValue = rating.values.getOrDefault(condition.rating, 1)
condition.result.takeIf { partValue in condition.range }
}
}
data class Condition(val rating: String, val range: IntRange, val result: WorkflowResult)
}
private sealed interface WorkflowResult {
data object Accepted : WorkflowResult
data object Rejected : WorkflowResult
data class Next(val workflow: String) : WorkflowResult
}
| 0 |
Kotlin
| 0 | 1 |
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
| 4,630 |
adventofcode
|
Apache License 2.0
|
src/Day08.kt
|
lsimeonov
| 572,929,910 | false |
{"Kotlin": 66434}
|
fun main() {
fun part1(input: List<String>): Int {
val stack = ArrayDeque<List<Int>>()
var i = 0
input.forEach {
stack.add(i, it.toList().map { c -> c.digitToInt() })
i++
}
val trees = stack.mapIndexed { n, cur ->
val nextRows = stack.filterIndexed { i, _ -> i > n }
val prevRows = stack.filterIndexed { i, _ -> i < n }
cur.filterIndexed { j, c ->
// Find all visibles
if (prevRows.isEmpty() || nextRows.isEmpty() || j == 0 || j == cur.size - 1) {
return@filterIndexed true
}
// look up to the end of edge
if (prevRows.find { it[j] >= c } == null) {
return@filterIndexed true
}
// look down to the end of edge
if (nextRows.find { it[j] >= c } == null) {
return@filterIndexed true
}
// look left to the end of the edge
if (cur.subList(0, j).find { it >= c } == null) {
return@filterIndexed true
}
// look right to the end of the edge
if (cur.subList(j + 1, cur.size).find { it >= c } == null) {
return@filterIndexed true
}
false
}.count()
}.sum()
return trees
}
fun part2(input: List<String>): Int {
val stack = ArrayDeque<List<Int>>()
var i = 0
input.forEach {
stack.add(i, it.toList().map { c -> c.digitToInt() })
i++
}
val trees = stack.mapIndexed { n, cur ->
val nextRows = stack.filterIndexed { i, _ -> i > n }
val prevRows = stack.filterIndexed { i, _ -> i < n }
cur.mapIndexed { j, c ->
// Find all visibles
if (prevRows.isEmpty() || nextRows.isEmpty() || j == 0 || j == cur.size - 1) {
return@mapIndexed 0
}
// look up to the end of edge
var up = 0
prevRows.reversed().find { up++; it[j] >= c }
// look down to the end of edge
var down = 0
nextRows.find { down++; it[j] >= c }
// look left to the end of the edge
var left = 0
cur.subList(0, j).reversed().find { left++; it >= c }
// look right to the end of the edge
var right = 0
cur.subList(j + 1, cur.size).find { right++; it >= c }
up * down * left * right
}.max()
}.max()
return trees
}
// 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 |
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
| 3,042 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day11.kt
|
cvb941
| 572,639,732 | false |
{"Kotlin": 24794}
|
data class Monkey(
var items: List<Long>,
val operation: (Long) -> Long,
val divisibleBy: Long,
val trueMonkey: Int,
val falseMonkey: Int,
var inspectCounter: Long = 0
) {
}
class Game(val monkeys: List<Monkey>, val worryReductionEnabled: Boolean) {
companion object {
fun parse(input: List<String>, worryReductionEnabled: Boolean): Game {
val monkeys = input.chunked(7) {
val items = it[1].substringAfter(":").split(",").map { it.trim().toLong() }
val operation = it[2].substringAfter("=").trim().split(" ").let {
when (it[1]) {
"+" -> { x: Long -> x + (it[2].toLongOrNull() ?: x) }
"*" -> { x: Long -> x * (it[2].toLongOrNull() ?: x) }
else -> throw IllegalArgumentException("Invalid operation: ${it[1]}")
}
}
val divisibleBy = it[3].split(" ").last().toLong()
val trueMonkey = it[4].split(" ").last().toInt()
val falseMonkey = it[5].split(" ").last().toInt()
Monkey(items, operation, divisibleBy, trueMonkey, falseMonkey)
}
return Game(monkeys, worryReductionEnabled)
}
}
val modulo = monkeys.map { it.divisibleBy }.reduce(Long::times)
fun round() {
monkeys.forEach { monkey ->
// Execute monkey turn
monkey.items.forEachIndexed { index, worryLevel ->
var newWorryLevel = monkey.operation(worryLevel)
if (worryReductionEnabled) newWorryLevel /= 3
val isDivisible = newWorryLevel % monkey.divisibleBy == 0L
val monkeyToThrowTo = if (isDivisible) monkey.trueMonkey else monkey.falseMonkey
monkeys[monkeyToThrowTo].items += newWorryLevel % modulo
monkey.inspectCounter++
}
monkey.items = emptyList()
}
}
}
fun main() {
fun part1(input: List<String>): Long {
val game = Game.parse(input, true)
repeat(20) {
game.round()
}
val score =
game.monkeys.sortedByDescending { it.inspectCounter }.take(2).map { it.inspectCounter }.reduce(Long::times)
return score
}
fun part2(input: List<String>): Long {
val game = Game.parse(input, false)
repeat(10000) {
game.round()
if (it % 1000 == 0) {
println("Round $it")
game.monkeys.forEachIndexed { index, monkey ->
println("Monkey $index: ${monkey.inspectCounter}")
}
}
}
val score =
game.monkeys.sortedByDescending { it.inspectCounter }.take(2).map { it.inspectCounter }.reduce(Long::times)
return score
}
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
fe145b3104535e8ce05d08f044cb2c54c8b17136
| 3,091 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/main/kotlin/aoc2020/ex18.kt
|
noamfree
| 433,962,392 | false |
{"Kotlin": 93533}
|
fun main() {
tests()
val input = readInputFile("aoc2020/input18")
print(input.lines().associateWith { calc(it) }.toList()
// .sortedBy { it.second }
.sumOf {
println("${it.first} = ${it.second}")
it.second
})
}
private fun tests() {
require(calc("1 + 2 * 3 + 4 * 5 + 6") == 71L)
require(calc("2 * 3 + (4 * 5)") == 26L)
require(calc("5 + (8 * 3 + 9 + 3 * 4 * 3)") == 437L)
require(calc("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))") == 12240L)
require(calc("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2") == 13632L)
require(calc("2* (1+1+(1+1))+1") == 9L)
// require(calc("4 * (4 + 7 + 4 * (9 * 2 + 3 * 9 * 8 * 7)) * (7 * 6 * 8) + 7 + 4 * 6") == 1280240706L)
}
//(3 + (5 * 5 * 2 * 2 + 4) + 7) + (8 * 6 * 8 * (7 + 9 + 3 + 8 + 3)) + (8 * 7) * (8 * 3 + 3 + 2 * (8 * 7 + 8 + 5) + 3) * 8
// 114 + (8 * 6 * 8 * (7 + 9 + 3 + 8 + 3)) + (8 * 7) * (8 * 3 + 3 + 2 * (8 * 7 + 8 + 5) + 3) * 8
// 114 + (384 * (7+9+3+8+3))
// 114 + 11520 + 54 * (8 * 3 + 3 + 2 * (8 * 7 + 8 + 5) + 3) * 8
// 114 + 11520 + 54 * (8 * 3 + 3 + 2 * 69 + 3) * 8
// 114 + 11520 + 54 * 2004 * 8
//8 + 7 * ((4 * 5 * 6 + 4 + 9) * 5) + 6 * ((8 + 2 * 4 * 9 * 8) * 6 * (4 + 2 * 8 + 2) * 9 + 3 * 2)
// 15 * ((4 * 5 * 6 + 4 + 9) * 5) + 6 * ((8 + 2 * 4 * 9 * 8) * 6 * (4 + 2 * 8 + 2) * 9 + 3 * 2)
// 15 * (133 * 5) + 6 * ((8 + 2 * 4 * 9 * 8) * 6 * (4 + 2 * 8 + 2) * 9 + 3 * 2)
// 15 * (133 * 5) + 6 * (2880 * 6 * (4 + 2 * 8 + 2) * 9 + 3 * 2)
// 9975 + 6 * (2880 * 6 * (4 + 2 * 8 + 2) * 9 + 3 * 2)
// 9981 * (2880 * 6 * 50 * 9 + 3 * 2)
// 9981 * 15552006
private enum class MathOperation {
ADD, MULTIPLY
}
private sealed class MathState {
class AfterOperation(val operation: MathOperation): MathState()
object AfterNumber: MathState()
object Init: MathState()
}
private fun calc(string: String) = Calculator().calculate(string, 0).first
private class Calculator {
var state: MathState = MathState.Init
var result = 0L
var currentIndex = 0
var string = ""
var ended = false
fun calculate(string: String, index: Int): Pair<Long, Int> {
this.string = string
currentIndex = index
while (currentIndex < string.length && !ended) {
handleChar(string[currentIndex])
currentIndex++
}
require(state is MathState.AfterNumber)
return result to currentIndex
}
private fun handleChar(char: Char) {
when (char) {
'(' -> {
val innerResult = Calculator().calculate(string, currentIndex + 1)
aggregateWithNumber(innerResult.first)
currentIndex = innerResult.second-1
}
')' -> {
require(state == MathState.AfterNumber)
ended = true
}
' ' -> Unit
'+' -> {
require(state is MathState.AfterNumber)
state = MathState.AfterOperation(MathOperation.ADD)
}
'*' -> {
require(state is MathState.AfterNumber)
state = MathState.AfterOperation(MathOperation.MULTIPLY)
}
else -> {
val number = char.toString().toLong()
aggregateWithNumber(number)
}
}
}
private fun aggregateWithNumber(number: Long) {
result = when (val state = state) {
is MathState.AfterOperation -> operate(result, state.operation, number)
is MathState.Init -> number
else -> error("currentIndex: $currentIndex, state $state")
}
state = MathState.AfterNumber
}
}
private fun operate(current: Long, operation: MathOperation, new: Long): Long {
return when (operation) {
MathOperation.ADD -> current + new
MathOperation.MULTIPLY -> current * new
}
}
| 0 |
Kotlin
| 0 | 0 |
566cbb2ef2caaf77c349822f42153badc36565b7
| 3,858 |
AOC-2021
|
MIT License
|
src/main/kotlin/day16/Day16.kt
|
TheSench
| 572,930,570 | false |
{"Kotlin": 128505}
|
package day16
import runDay
fun main() {
fun part1(input: List<String>) = input.parse()
.let { rooms ->
val stack = listOf(
RoomState(emptySet(), listOf("AA"))
)
(1..30).fold(stack) { statesAtThisStep, i ->
println(i)
statesAtThisStep.flatMap { it.getTransitions(rooms) }
.distinct().sortedByDescending { it.relieved + it.relieving }.take(500)
}.maxOf { it.relieved }
}
fun part2(input: List<String>) = input.parse()
.let { rooms ->
val stack = listOf(
RoomState(emptySet(), listOf("AA", "AA"))
)
(1..26).fold(stack) { statesAtThisStep, i ->
println(i)
statesAtThisStep.flatMap { it.getTransitions(rooms) }
.distinct().sortedByDescending { it.relieved + it.relieving }.take(500)
}.maxOf { it.relieved }
}
(object {}).runDay(
part1 = ::part1,
part1Check = 1651,
part2 = ::part2,
part2Check = 1707,
)
}
data class Room(
val name: String,
val flowRate: Int,
val connected: List<String>,
)
fun List<String>.parse() = map { it.toRoom() }.associateBy { it -> it.name }
val roomRegex = Regex("""Valve (\w+) has flow rate=([\d-]+); tunnels? leads? to valves? (.*)""")
fun String.toRoom(): Room {
val match = roomRegex.matchEntire(this)
val (
name,
rate,
connected,
) = match!!.destructured
return Room(
name,
rate.toInt(),
connected.split(", ")
)
}
typealias Rooms = Map<String, Room>
fun RoomState.getTransitions(rooms: Rooms): List<RoomState> {
val after1Minute = copy(
current = emptyList(),
relieved = relieved + relieving
)
return current.fold(listOf(after1Minute)) { states, currentRoom ->
states.flatMap { getTransitions(it, currentRoom, rooms) }
}.map {
it.copy(current = it.current.sorted())
}
}
fun getTransitions(baseState: RoomState, currentRoom: String, rooms: Rooms): List<RoomState> {
val room = rooms[currentRoom]
val options = room!!.connected.map { newRoom ->
baseState.copy(
current = baseState.current + newRoom,
)
}
return if (baseState.enabledRooms.contains(currentRoom)) {
options
} else {
options + baseState.copy(
current = baseState.current + currentRoom,
enabledRooms = baseState.enabledRooms + currentRoom,
relieving = baseState.relieving + room.flowRate,
)
}
}
data class RoomState(
val enabledRooms: Set<String>,
val current: List<String>,
val relieving: Int = 0,
val relieved: Int = 0,
)
| 0 |
Kotlin
| 0 | 0 |
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
| 2,793 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/Excercise22.kt
|
underwindfall
| 433,989,850 | false |
{"Kotlin": 55774}
|
private data class ModInstruction(
val on: Boolean,
val x1: Int,
val x2: Int,
val y1: Int,
val y2: Int,
val z1: Int,
val z2: Int
)
private val input = parseInput(getInputAsTest("22"))
private fun parseInput(input: List<String>): List<ModInstruction> {
val regex = Regex("x=([-\\d]+)..([-\\d]+),y=([-\\d]+)..([-\\d]+),z=([-\\d]+)..([-\\d]+)")
return input.map {
val l = regex.matchEntire(it.substringAfter(" "))!!.groupValues.drop(1).map(String::toInt)
ModInstruction("on" in it, l[0], l[1], l[2], l[3], l[4], l[5])
}
}
private fun part1() {
val instructions =
input.filter { instruction ->
instruction.run { listOf(x1, x2, y1, y2, z1, z2).all { it in -50..50 } }
}
val cubes = List(101) { List(101) { MutableList(101) { false } } }
instructions.forEach {
for (x in it.x1..it.x2) for (y in it.y1..it.y2) for (z in it.z1..it.z2) cubes[x + 50][y + 50][
z + 50] = it.on
}
println("Part 1 ${ cubes.flatten().flatten().count { it }}")
}
private fun part2() {
val instructions = input
val cubes = mutableListOf<ModInstruction>()
instructions.forEach {
val overlaps = mutableListOf<ModInstruction>()
cubes.forEach { cube ->
val x1 = maxOf(it.x1, cube.x1)
val x2 = minOf(it.x2, cube.x2)
val y1 = maxOf(it.y1, cube.y1)
val y2 = minOf(it.y2, cube.y2)
val z1 = maxOf(it.z1, cube.z1)
val z2 = minOf(it.z2, cube.z2)
if (x1 <= x2 && y1 <= y2 && z1 <= z2)
overlaps.add(ModInstruction(!cube.on, x1, x2, y1, y2, z1, z2))
}
cubes.addAll(overlaps)
if (it.on) cubes.add(it)
}
println("Part 2")
println(
cubes.sumOf {
(if (it.on) 1L else -1L) * (it.x2 - it.x1 + 1) * (it.y2 - it.y1 + 1) * (it.z2 - it.z1 + 1)
}
)
}
fun main() {
part1()
part2()
}
| 0 |
Kotlin
| 0 | 0 |
4fbee48352577f3356e9b9b57d215298cdfca1ed
| 1,794 |
advent-of-code-2021
|
MIT License
|
07.kts
|
pin2t
| 725,922,444 | false |
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
|
val chars = arrayOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2')
enum class Type { HIGH, ONE_PAIR, TWO_PAIR, THREE_OF_KIND, FULL_HOUSE, FOUR_OF_KIND, FIVE_OF_KIND }
data class Hand(val cards: String): Comparable<Hand> {
fun type(): Type {
val counts = HashMap<Char, Int>(5)
cards.forEach { counts.merge(it, 1, Int::plus) }
val s = counts.values.toList().sorted()
if (s.size == 1) return Type.FIVE_OF_KIND
if (s.size == 2 && s[0] == 1) return Type.FOUR_OF_KIND
if (s.size == 2 && s[0] == 2 && s[1] == 3) return Type.FULL_HOUSE
if (s.find { it == 3 } != null) return Type.THREE_OF_KIND
if (s.size == 3 && s[0] == 1 && s[1] == 2 && s[2] == 2) return Type.TWO_PAIR
if (s.size == 4 && s[0] == 1 && s[1] == 1 && s[2] == 1 && s[3] == 2) return Type.ONE_PAIR
return Type.HIGH
}
override fun compareTo(other: Hand): Int {
if (other.type().ordinal < this.type().ordinal) return 1
if (other.type().ordinal > this.type().ordinal) return -1;
for (i in cards.indices) {
if (chars.indexOf(this.cards[i]) < chars.indexOf(other.cards[i])) return 1
if (chars.indexOf(this.cards[i]) > chars.indexOf(other.cards[i])) return -1
}
return 0
}
}
data class BestHand(val hand: Hand): Comparable<BestHand> {
constructor(cards: String): this(hand = Hand(cards))
fun type(): Type {
return chars.map { Hand(hand.cards.replace('J', it)).type() }.maxBy { it.ordinal }
}
override fun compareTo(other: BestHand): Int {
if (other.type().ordinal < this.type().ordinal) return 1
if (other.type().ordinal > this.type().ordinal) return -1;
val chars = arrayOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J')
for (i in this.hand.cards.indices) {
if (chars.indexOf(this.hand.cards[i]) < chars.indexOf(other.hand.cards[i])) return 1
if (chars.indexOf(this.hand.cards[i]) > chars.indexOf(other.hand.cards[i])) return -1
}
return 0
}
}
val input = System.`in`.bufferedReader().readLines()
val hands = ArrayList<Pair<Hand, Int>>(input.map {Pair(Hand(it.split(" ")[0]), it.split(" ")[1].toInt()) }.toList()).sortedBy { it.first }
val besthands = ArrayList<Pair<BestHand, Int>>(input.map {Pair(BestHand(it.split(" ")[0]), it.split(" ")[1].toInt()) }.toList()).sortedBy { it.first }
val total = hands.indices.map { (it + 1) * hands[it].second }.reduce(Int::plus)
val bestTotal = besthands.indices.map { (it + 1) * besthands[it].second }.reduce(Int::plus)
println("$total $bestTotal")
| 0 |
Kotlin
| 1 | 0 |
7575ab03cdadcd581acabd0b603a6f999119bbb6
| 2,639 |
aoc2023
|
MIT License
|
src/Day12.kt
|
ZiomaleQ
| 573,349,910 | false |
{"Kotlin": 49609}
|
import java.util.PriorityQueue
fun main() {
fun part1(input: List<String>): Int {
var start = Cords(0, 0)
var end = Cords(0, 0)
val heatmap = input.flatMapIndexed { y, row ->
row.mapIndexed { x, elt ->
val here = Cords(x, y)
here to when (elt) {
'E' -> 25.also { end = Cords(x, y) }
'S' -> 0.also { start = Cords(x, y) }
else -> elt - 'a'
}
}
}.toMap()
val grid = Grid(input)
return grid.findCost(
start,
isEnd = { it == end },
canMove = { from, to -> heatmap[to]!! - heatmap[from]!! <= 1 },
)
}
fun part2(input: List<String>): Int {
var end = Cords(0, 0)
val heatmap = input.flatMapIndexed { y, row ->
row.mapIndexed { x, elt ->
val here = Cords(x, y)
here to when (elt) {
'E' -> 25.also { end = Cords(x, y) }
// 'S' -> 0.also { start = Cords(x, y) }
else -> elt - 'a'
}
}
}.toMap()
val grid = Grid(input)
return grid.findCost(
end,
isEnd = { heatmap[it] == 0 },
canMove = { from, to -> heatmap[from]!! - heatmap[to]!! <= 1 },
)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
part1(testInput).also { println(it); check(it == 31) }
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
private fun Cords.checkBoundary(height: Int, width: Int) = this.x in 0 until width && this.y in 0 until height
private class Grid(input: List<String>) {
val height = input.size
val width = input[0].length
val visited = List(width) { BooleanArray(height) { false } }
fun findCost(
start: Cords,
isEnd: (Cords) -> Boolean,
canMove: (Cords, Cords) -> Boolean
): Int {
val queue = PriorityQueue<PathCost>().apply { add(PathCost(start, 0)) }
while (true) {
val latest = queue.poll()
val cord = latest.cord
if (visited[cord.x][cord.y]) {
continue
} else {
visited[cord.x][cord.y] = true
}
val segmentsToMove = listOf(
Cords(cord.x + 1, cord.y),
Cords(cord.x - 1, cord.y),
Cords(cord.x, cord.y + 1),
Cords(cord.x, cord.y - 1)
)
.filter { it.checkBoundary(height, width) }
.filter { canMove(cord, it) }
if (segmentsToMove.any(isEnd)) {
return latest.cost + 1
}
queue.addAll(segmentsToMove.map { PathCost(it, latest.cost + 1) })
}
}
data class PathCost(val cord: Cords, val cost: Int) : Comparable<PathCost> {
override fun compareTo(other: PathCost): Int =
this.cost.compareTo(other.cost)
}
}
| 0 |
Kotlin
| 0 | 0 |
b8811a6a9c03e80224e4655013879ac8a90e69b5
| 3,126 |
aoc-2022
|
Apache License 2.0
|
src/day3/puzzle03.kt
|
brendencapps
| 572,821,792 | false |
{"Kotlin": 70597}
|
package day3
import Puzzle
import PuzzleInput
import java.io.File
fun day3Puzzle() {
val inputDir = "inputs/day3"
Day3Puzzle1Solution().solve(Day3PuzzleInput("$inputDir/example.txt", 157))
Day3Puzzle1Solution().solve(Day3PuzzleInput("$inputDir/input.txt", 8039))
Day3Puzzle2Solution().solve(Day3PuzzleInput("$inputDir/example.txt", 70))
Day3Puzzle2Solution().solve(Day3PuzzleInput("$inputDir/input.txt", 2510))
}
class Day3PuzzleInput(private val input: String, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) {
fun sum(op: (String) -> Int): Int {
return File(input).readLines().sumOf { rucksack -> op(rucksack) }
}
fun sum(chunk: Int, op: (List<String>) -> Int): Int {
return File(input).readLines().chunked(chunk).sumOf { rucksack -> op(rucksack) }
}
}
class Day3Puzzle1Solution : Puzzle<Int, Day3PuzzleInput>() {
override fun solution(input: Day3PuzzleInput): Int {
return input.sum { rucksack ->
val common = rucksack.substring(0 until rucksack.length / 2)
.toSet()
.intersect(rucksack.substring(rucksack.length / 2).toSet())
check(common.size == 1)
common.first().priority()
}
}
}
class Day3Puzzle2Solution : Puzzle<Int, Day3PuzzleInput>() {
override fun solution(input: Day3PuzzleInput): Int {
return input.sum(3) { rucksacks ->
var set = rucksacks[0].toSet()
for(i in 1 until rucksacks.size) {
set = set.intersect(rucksacks[i].toSet())
}
check(set.size == 1)
set.first().priority()
}
}
}
fun Char.priority(): Int {
check(isLetter())
return if(isLowerCase()) {
this - 'a' + 1
}
else {
this - 'A' + 27
}
}
| 0 |
Kotlin
| 0 | 0 |
00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3
| 1,874 |
aoc_2022
|
Apache License 2.0
|
src/y2022/Day12.kt
|
gaetjen
| 572,857,330 | false |
{"Kotlin": 325874, "Mermaid": 571}
|
package y2022
import util.Direction
import util.Pos
import util.readInput
object Day12 {
private fun parse(input: List<String>): Triple<List<List<Int>>, Pos, Pos> {
var start: Pos = 0 to 0
var end: Pos = 0 to 0
val grid = input.mapIndexed { rowIdx, row ->
row.mapIndexed { colIdx, char ->
when (char) {
'S' -> {
start = rowIdx to colIdx
0
}
'E' -> {
end = rowIdx to colIdx
25
}
else -> (char - 'a')
}
}
}
return Triple(grid, start, end)
}
private fun getNeighbors(grid: List<List<Int>>, pos: Pos): List<Pos> {
val height = grid[pos]
return Direction.entries.map {
it.move(pos)
}.filter { (r, c) -> r in grid.indices && c in grid[r].indices }
.filter { grid[it] <= height + 1 }
}
private fun getReverseNeighbors(grid: List<List<Int>>, pos: Pos): List<Pos> {
val height = grid[pos]
return Direction.entries.map {
it.move(pos)
}.filter { (r, c) -> r in grid.indices && c in grid[r].indices }
.filter { grid[it] >= height - 1 }
}
fun part1(input: List<String>): Int {
val (grid, start, end) = parse(input)
val unvisited = grid.indices.map { rowIdx ->
grid[rowIdx].indices.map { rowIdx to it }
}.flatten().toMutableSet()
unvisited.remove(start)
var numSteps = 0
var frontier = setOf(start)
while (end in unvisited) {
numSteps++
// get all neighbors
val allNeighbors = frontier.map { getNeighbors(grid, it) }.flatten().toSet()
frontier = allNeighbors.intersect(unvisited)
// remove from unvisited
unvisited.removeAll(frontier)
}
return numSteps
}
operator fun List<List<Int>>.get(p: Pos): Int {
return this[p.first][p.second]
}
fun part2(input: List<String>): Int {
val (grid, _, end) = parse(input)
val unvisited = grid.indices.map { rowIdx ->
grid[rowIdx].indices.map { rowIdx to it }
}.flatten().toMutableSet()
unvisited.remove(end)
var numSteps = 0
var frontier = setOf(end)
while (frontier.all { grid[it] > 0 }) {
numSteps++
// get all neighbors
val allNeighbors = frontier.map { getReverseNeighbors(grid, it) }.flatten().toSet()
frontier = allNeighbors.intersect(unvisited)
// remove from unvisited
unvisited.removeAll(frontier)
}
return numSteps
}
}
fun main() {
val testInput = """
Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi
""".trimIndent().split("\n")
println("------Tests------")
println(Day12.part1(testInput))
println(Day12.part2(testInput))
println("------Real------")
val input = readInput("resources/2022/day12")
println(Day12.part1(input))
println(Day12.part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
| 3,226 |
advent-of-code
|
Apache License 2.0
|
src/day08/Day08.kt
|
scottpeterson
| 573,109,888 | false |
{"Kotlin": 15611}
|
package day08
import readInput
// take the input of lines of strings, put into lines, put into chars, convert to Ints
private fun constructForest(input: List<String>): List<List<Int>> {
return input.map { line ->
line.toCharArray().map { Integer.parseInt("$it") }
}
}
// for each "tree", calculate if it's visible at all
private fun canISee(forest: List<List<Int>>, row: Int, column: Int): Boolean {
val treeHeight = forest[row][column]
val visibleFromTop = forest.map { it[column] }.subList(0, row).max() < treeHeight
val visibleFromEnd = forest[row].subList(column+1, forest[row].size).max() < treeHeight
val visibleFromBottom = forest.map { it[column] }.subList(row + 1, forest.map { it[column] }.size).max() < treeHeight
val visibleFromStart = forest[row].subList(0, column).max() < treeHeight
return visibleFromTop || visibleFromEnd || visibleFromBottom || visibleFromStart
}
private fun optimalTree(forest: List<List<Int>>, row: Int, column: Int): Int {
val treeHeight = forest[row][column]
var distanceToStart = 0
for (i in column - 1 downTo 0 ) {
++distanceToStart
if (treeHeight <= forest[row][i]) {
break
}
}
var distanceToEnd = 0
for (i in column + 1 until forest[row].size) {
++distanceToEnd
if (treeHeight <= forest[row][i]) {
break
}
}
var distanceToTop = 0
for (i in row - 1 downTo 0) {
distanceToTop += 1
if (treeHeight <= forest[i][column]) {
break
}
}
var distanceToBottom = 0
for (i in row + 1 until forest.size) {
distanceToBottom += 1
if (treeHeight <= forest[i][column]) {
break
}
}
return distanceToStart * distanceToEnd * distanceToTop * distanceToBottom
}
fun partOne(input: List<String>): Int {
val forest = constructForest(input)
var countVisible = input.first().length * 2 + (input.size - 2) * 2
for (i in 1..forest.first().size - 2) {
for (j in 1..forest[i].size - 2) {
if (canISee(forest, i, j)) {
++countVisible
}
}
}
return countVisible
}
fun partTwo(input: List<String>): Int {
val forest = constructForest(input)
var runningLargest = 0
forest.forEachIndexed { i, row ->
row.forEachIndexed { j, I ->
val viewingDistance = optimalTree(forest, i, j)
if (viewingDistance > runningLargest) {
runningLargest = viewingDistance
}
}
}
return runningLargest
}
fun main() {
println(partOne((readInput("day08/Day08_input"))))
println(partTwo((readInput("day08/Day08_input"))))
}
| 0 |
Kotlin
| 0 | 0 |
0d86213c5e0cd5403349366d0f71e0c09588ca70
| 2,733 |
advent-of-code-2022
|
Apache License 2.0
|
src/year2021/day12/Day12.kt
|
fadi426
| 433,496,346 | false |
{"Kotlin": 44622}
|
package year2021.day01.day12
import util.assertTrue
import util.model.Counter
import util.read2021DayInput
fun main() {
fun task01(input: List<String>): Int {
val caves = createCaves(input)
val startCave = caves.first { it.name == "start" }
val counter = Counter()
navigate(startCave, mutableListOf(startCave), counter, false)
return counter.i
}
fun task02(input: List<String>): Int {
val caves = createCaves(input)
val startCave = caves.first { it.name == "start" }
val counter = Counter()
navigate(startCave, mutableListOf(startCave), counter, true)
return counter.i
}
val input = read2021DayInput("Day12")
assertTrue(task01(input) == 5157)
assertTrue(task02(input) == 144309)
}
fun navigate(cave: Cave, visited: MutableList<Cave>, counter: Counter, withSingleRevisit: Boolean) {
cave.nearbyCaves.forEach { nearbyCave ->
if (nearbyCave.nearbyCaves.isEmpty()) counter.i++
else {
val visitedSmallCaveTwice =
visited.map { cave -> visited.count { it == cave && it.isSmallCave() } }.any { it > 1 }
if (!visitedSmallCaveTwice && withSingleRevisit) {
navigate(nearbyCave, (mutableListOf(nearbyCave) + visited).toMutableList(), counter, withSingleRevisit)
} else {
if (visited.contains(nearbyCave) && nearbyCave.isSmallCave()) return@forEach
navigate(nearbyCave, (mutableListOf(nearbyCave) + visited).toMutableList(), counter, withSingleRevisit)
}
}
}
}
fun createCaves(input: List<String>): List<Cave> {
val caves = input.map { it.split("-") }.flatten().distinct()
.map { Cave(it) }
input.forEach {
val cavePair = it.split('-')
if (cavePair[1] != "start")
if (cavePair[0] != "end") {
caves.first { it.name == cavePair[0] }.addNearbyCave(caves.first { it.name == cavePair[1] })
}
if (cavePair[0] != "start")
if (cavePair[1] != "end")
caves.first { it.name == cavePair[1] }.addNearbyCave(caves.first { it.name == cavePair[0] })
}
return caves
}
data class Cave(val name: String) {
val nearbyCaves = mutableListOf<Cave>()
fun isSmallCave(): Boolean {
return name[0].isLowerCase() && name != "start" && name != "end"
}
fun addNearbyCave(cave: Cave) {
nearbyCaves.add(cave)
}
}
| 0 |
Kotlin
| 0 | 0 |
acf8b6db03edd5ff72ee8cbde0372113824833b6
| 2,483 |
advent-of-code-kotlin-template
|
Apache License 2.0
|
src/Day02.kt
|
zuevmaxim
| 572,255,617 | false |
{"Kotlin": 17901}
|
private enum class Element(val score: Int) {
Rock(1), Paper(2), Scissors(3);
fun roundScore(other: Element): Int {
if (this == other) return 3
if ((this.ordinal + 1) % 3 == other.ordinal) return 0
return 6
}
}
private enum class Result(val shift: Int) {
Win(1), Draw(0), Lose(-1);
fun findAnswer(element: Element): Element {
return Element.values()[(element.ordinal + shift + 3) % 3]
}
}
private val elementNames = hashMapOf(
"A" to Element.Rock, "B" to Element.Paper, "C" to Element.Scissors,
"X" to Element.Rock, "Y" to Element.Paper, "Z" to Element.Scissors,
)
private val resultNames = hashMapOf("X" to Result.Lose, "Y" to Result.Draw, "Z" to Result.Win)
private fun part1(input: List<String>): Int {
return input.sumOf { round ->
val (a, b) = round.split(" ").map { elementNames[it]!! }
b.score + b.roundScore(a)
}
}
private fun part2(input: List<String>): Int {
return input.sumOf { round ->
val (a, b) = round.split(" ")
val other = elementNames[a]!!
val result = resultNames[b]!!
val answer = result.findAnswer(other)
answer.score + answer.roundScore(other)
}
}
fun main() {
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 |
34356dd1f6e27cc45c8b4f0d9849f89604af0dfd
| 1,429 |
AOC2022
|
Apache License 2.0
|
src/Day03.kt
|
binaryannie
| 573,120,071 | false |
{"Kotlin": 10437}
|
private const val DAY = "03"
private const val PART_1_CHECK = 157
private const val PART_2_CHECK = 70
fun codeToPriority (code: Int): Int {
return if (code <= 90) code - 65 + 27 else code - 96
}
// a is worth 1, z is worth 26, A is worth 27, Z is worth 52
fun main() {
fun part1(input: List<String>): Int {
val rucksacks = input
.map { it.chunked(it.length / 2)
.map { chunk -> chunk.toCharArray().toSet() }
}
val duplicates = rucksacks.map {
var duplicate: Char? = null
it[0].forEach { c -> if (it[1].contains(c)) duplicate = c }
duplicate
}
return duplicates.map { codeToPriority(it!!.code) }.sum()
}
fun part2(input: List<String>): Int {
val duplicates = input
.chunked(3)
.map {
var duplicate: Char? = null
it[0].forEach { c -> if (it[1].contains(c) && it[2].contains(c)) duplicate = c }
duplicate
}
return duplicates.map { codeToPriority(it!!.code) }.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${DAY}_test")
check(part1(testInput).also { println("Part 1 check: $it") } == PART_1_CHECK)
check(part2(testInput).also { println("Part 2 check: $it") } == PART_2_CHECK)
val input = readInput("Day${DAY}")
println("Part 1 solution: ${part1(input)}")
println("Part 2 solution: ${part2(input)}")
}
| 0 |
Kotlin
| 0 | 0 |
511fc33f9dded71937b6bfb55a675beace84ca22
| 1,540 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day03.kt
|
WhatDo
| 572,393,865 | false |
{"Kotlin": 24776}
|
fun main() {
val rucksacks = readInput("Day03").map { rucksack ->
val (first, second) = rucksack
.toList()
.let { list ->
list.subList(0, rucksack.length / 2) to list.subList(rucksack.length / 2, list.size)
}
Rucksack(Compartment(first.toSet()), Compartment(second.toSet()))
}
val summedPriority = rucksacks.sumOf { rucksack ->
rucksack.first.overlap(rucksack.second).also {
println("${rucksack.first.items} overlaps with ${rucksack.second.items} by $it (${it.first().priority})")
}.sumOf { it.priority }
}
println("Total sum of priority is $summedPriority")
val badges = rucksacks.windowed(3, 3) { sacks ->
sacks.fold(sacks.first().allItems) { acc, sack ->
acc.intersect(sack.allItems).also { println(sack.allItems) }
}.also {
println("Common item is $it")
}
}.sumOf { it.sumOf { it.priority } }
println("Sum of badge icons is $badges")
}
data class Rucksack(
val first: Compartment,
val second: Compartment
) {
val allItems = first.items + second.items
}
class Compartment(
val items: Set<Char>
)
fun Compartment.overlap(other: Compartment) = items.intersect(other.items)
val Char.priority
get() = if (isLowerCase()) {
code - 'a'.code + 1
} else {
code - 'A'.code + 27
}
| 0 |
Kotlin
| 0 | 0 |
94abea885a59d0aa3873645d4c5cefc2d36d27cf
| 1,403 |
aoc-kotlin-2022
|
Apache License 2.0
|
src/main/kotlin/day5/Day5.kt
|
cyril265
| 433,772,262 | false |
{"Kotlin": 39445, "Java": 4273}
|
package day5
import readToList
val input = readToList("day5.txt")
fun main() {
println(part1())
println(part2())
}
private fun part1() {
val validLines = input
.map { line ->
val (first, second) = line.split(" -> ")
Line(toPoint(first), toPoint(second))
}
.filter { it.notDiagonal() }
val resultPoints = validLines.flatMap { line -> line.producePoints() }
val groupedByPoints = resultPoints
.groupingBy { it }
.eachCount()
println(groupedByPoints.values.count { it >= 2 })
}
private fun part2() {
val validLines = input
.map { line ->
val (first, second) = line.split(" -> ")
Line(toPoint(first), toPoint(second))
}
val resultPoints = validLines.flatMap { line -> line.producePoints() }
val groupedByPoints = resultPoints
.groupingBy { it }
.eachCount()
println(groupedByPoints.values.count { it >= 2 })
}
private fun toPoint(first: String): Point {
val (x, y) = first.split(",").map { it.toInt() }
return Point(x, y)
}
data class Line(val a: Point, val b: Point) {
fun notDiagonal() = isHorizontal() || isVertical()
fun isHorizontal() = a.x == b.x
fun isVertical() = a.y == b.y
fun producePoints(): List<Point> {
return if (isHorizontal()) {
val range = if (a.y < b.y) a.y..b.y else b.y..a.y
range.map { Point(a.x, it) }
} else if (isVertical()) {
val range = if (a.x < b.x) a.x..b.x else b.x..a.x
range.map { Point(it, a.y) }
} else {
val range = if (a.x < b.x) a.x..b.x else b.x..a.x
val pts = range.map { Point(it, it) }
pts
}
}
}
data class Point(val x: Int, val y: Int)
| 0 |
Kotlin
| 0 | 0 |
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
| 1,795 |
aoc2021
|
Apache License 2.0
|
src/Day08.kt
|
f1qwase
| 572,888,869 | false |
{"Kotlin": 33268}
|
private data class ViewingDistance(
val left: Int,
val top: Int,
val right: Int,
val bottom: Int,
) {
fun score(): Int {
return (left * top * right * bottom)
}
}
private class Tree(val height: Int) {
var left: Tree? = null
var top: Tree? = null
var right: Tree? = null
var bottom: Tree? = null
val viewingDistance: ViewingDistance
get() {
fun getViewingDistance(s: Sequence<Tree>): Int = s.indexOfFirst { it.height >= height }.let {
if (it == -1) s.count() else it + 1
}
return ViewingDistance(
left = generateSequence(left) { it.left }.let(::getViewingDistance),
top = generateSequence(top) { it.top }.let(::getViewingDistance),
right = generateSequence(right) { it.right }.let(::getViewingDistance),
bottom = generateSequence(bottom) { it.bottom }.let(::getViewingDistance),
)
}
override fun toString(): String {
return "Tree(height=$height, left=${left?.height}, top=${top?.height}, right=${right?.height}, bottom=${bottom?.height})"
}
}
private fun parseTrees(input: List<String>): Array<Array<Tree>> {
val trees = input.map { it.toCharArray() }
val width = input.map { it.length }.distinct().singleOrNull()
?: throw IllegalArgumentException("Input is not rectangular")
val height = input.size
val treeMatrix = Array(height) { y -> Array(width) { x -> Tree(input[y][x].toString().toInt()) } }
for (y in trees.indices) {
for (x in trees[y].indices) {
val tree = treeMatrix[y][x]
if (x > 0) {
tree.left = treeMatrix[y][x - 1]
}
if (y > 0) {
tree.top = treeMatrix[y - 1][x]
}
if (x < trees[y].size - 1) {
tree.right = treeMatrix[y][x + 1]
}
if (y < trees.size - 1) {
tree.bottom = treeMatrix[y + 1][x]
}
}
}
return treeMatrix
}
fun main() {
fun part1(input: List<String>): Int {
val width = input.map { it.length }.distinct().singleOrNull()
?: throw IllegalArgumentException("Input is not rectangular")
val height = input.size
val visibilityMap = Array(height) { Array(width) { false } }
val treesHeightMap = input.map { it.map { char -> char.toString().toInt() } }
treesHeightMap.forEachIndexed { y, line ->
var highestFromLeft = -1
line.forEachIndexed { x, height ->
if (height > highestFromLeft) {
visibilityMap[y][x] = true
highestFromLeft = height
}
}
var highestFromRight = -1
line.indices.reversed().forEach { x ->
if (line[x] > highestFromRight) {
visibilityMap[y][x] = true
highestFromRight = line[x]
}
}
}
(0 until width).forEach { x ->
var highestFromTop = -1
(0 until height).forEach { y ->
if (treesHeightMap[y][x] > highestFromTop) {
visibilityMap[y][x] = true
highestFromTop = treesHeightMap[y][x]
}
}
var highestFromBottom = -1
(height - 1 downTo 0).forEach { y ->
if (treesHeightMap[y][x] > highestFromBottom) {
visibilityMap[y][x] = true
highestFromBottom = treesHeightMap[y][x]
}
}
}
return visibilityMap.sumOf { line -> line.count { it } }
}
fun part2(input: List<String>): Int {
val trees = parseTrees(input)
trees.joinToString("\n") {
it.joinToString("") { it.viewingDistance.score().toString() }
}.let(::println)
// println(trees[3][2].viewingDistance)
println(trees[1][2].viewingDistance)
var bestTree: Tree? = null
var bestTreeCoords: Pair<Int, Int>? = null
trees.forEach { line->
line.forEach {
if (bestTree == null || it.viewingDistance.score() > bestTree!!.viewingDistance.score()) {
bestTree = it
bestTreeCoords = Pair(trees.indexOf(line), line.indexOf(it))
}
}
}
println(bestTree)
println(bestTreeCoords)
return trees.flatten().map { it.viewingDistance.score() }.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21) {
part1(testInput)
}
val input = readInput("Day08")
println(part1(input))
check(part2(testInput) == 8) { part2(testInput) }
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
3fc7b74df8b6595d7cd48915c717905c4d124729
| 4,918 |
aoc-2022
|
Apache License 2.0
|
src/Day03.kt
|
tblechmann
| 574,236,696 | false |
{"Kotlin": 5756}
|
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val leftDistinct = rucksack.take(rucksack.length / 2).toCharArray().distinct()
val rightDistinct = rucksack.takeLast(rucksack.length / 2).toCharArray().distinct()
val merged = leftDistinct + rightDistinct
val mergedDistinct = merged.distinct().toMutableList().apply { add('#') }
val difference = merged.zip(mergedDistinct).map { it.first.code - it.second.code }
val char = difference.indexOfFirst { it != 0 }.let { merged[it!!] }
val charValue = (char.lowercaseChar() - 'a' + 1) + (if (char.isUpperCase()) 26 else 0)
charValue
}
}
fun part2(input: List<String>): Int {
val result = input.windowed(3, 3).sumOf { group ->
val distinctValues = group.map { it.toCharArray().distinct() }
val merged = distinctValues[0] + distinctValues[1] + distinctValues[2]
val charCounter = Array<Int>(26 * 2) { 0 }
merged.forEach {
charCounter[(it.lowercaseChar() - 'a') + (if (it.isUpperCase()) 26 else 0)]++
}
val charValue = charCounter.indexOfFirst { it == 3 } + 1
charValue
}
return result
}
// 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 |
4a65f6468a0cddd8081f2f0e3c1a96935438755f
| 1,596 |
aoc2022
|
Apache License 2.0
|
src/main/kotlin/aoc22/Day02.kt
|
asmundh
| 573,096,020 | false |
{"Kotlin": 56155}
|
package aoc22
import readInput
fun getScore(yourPick: Hands, opponentPick: Hands): Int {
val roundScore = when (yourPick) {
Hands.ROCK -> when (opponentPick) {
Hands.ROCK -> Scores.DRAW
Hands.SCISSOR -> Scores.WIN
Hands.PAPER -> Scores.LOSS
}
Hands.PAPER -> when (opponentPick) {
Hands.ROCK -> Scores.WIN
Hands.SCISSOR -> Scores.LOSS
Hands.PAPER -> Scores.DRAW
}
Hands.SCISSOR -> when (opponentPick) {
Hands.ROCK -> Scores.LOSS
Hands.PAPER -> Scores.WIN
Hands.SCISSOR -> Scores.DRAW
}
}
return roundScore.score + yourPick.score
}
enum class Hands(
val score: Int,
private val losesTo: String,
private val winsOver: String
) {
ROCK(1, "PAPER", "SCISSOR"),
PAPER(2, "SCISSOR", "ROCK"),
SCISSOR(3, "ROCK", "PAPER");
fun getHandForStrategy(strategy: Strategy): Hands =
when (strategy) {
Strategy.WIN -> Hands.valueOf(losesTo)
Strategy.DRAW -> this
Strategy.LOSE -> Hands.valueOf(winsOver)
}
companion object {
fun from(shortName: String): Hands =
when (shortName) {
"X", "A" -> ROCK
"Y", "B" -> PAPER
"Z", "C" -> SCISSOR
else -> throw Exception("Nei nei nei: $shortName")
}
}
}
enum class Strategy() {
LOSE,
WIN,
DRAW;
companion object {
fun from(shortHand: String): Strategy = when (shortHand) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw Exception("Huff da")
}
}
}
enum class Scores(val score: Int) {
DRAW(3),
LOSS(0),
WIN(6);
}
fun day2part1(input: List<String>): Int =
input.sumOf {
val hands = it.split(" ")
getScore(Hands.from(hands[1]), Hands.from(hands[0]))
}
fun day2part2(input: List<String>): Int = input.sumOf {
val strategy = it.split(" ")
val opponentsHand = Hands.from(strategy[0])
getScore(
opponentsHand.getHandForStrategy(Strategy.from(strategy[1])),
opponentsHand
)
}
fun main() {
val input = readInput("Day02")
println(day2part1(input))
println(day2part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
7d0803d9b1d6b92212ee4cecb7b824514f597d09
| 2,314 |
advent-of-code
|
Apache License 2.0
|
src/Day02.kt
|
binaryannie
| 573,120,071 | false |
{"Kotlin": 10437}
|
fun convertInputToGames(input: List<String>): List<List<Int>> {
return input
.map { it.split(' ') }
.map { listOf(it[0].toCharArray()[0].code - 65, it[1].toCharArray()[0].code - 88) }
}
fun scoreGame (opponentPlays: Int, wePlay: Int): Int {
val playerScore = wePlay + 1
return when (opponentPlays) {
wePlay -> 3 + playerScore // Draw
(wePlay + 1) % 3 -> playerScore // Lose
else -> 6 + playerScore // Win
}
}
// 0 = rocks, 1 = paper, 2 = scissors
// 0 wins against 2 but loses against 1
// 1 wins against 0 but loses against 2
// 2 wins against 1 but loses against 0
fun main() {
fun part1(input: List<String>): Int {
val games = convertInputToGames(input)
val scores = games
.map {
scoreGame(it[0], it[1])
}
return scores.sum()
}
// 0 = Lose, 1 = Draw, 2 = Win
fun part2(input: List<String>): Int {
val games = convertInputToGames(input)
val scores = games
.map {
val result = it[1]
val opponentPlays = it[0]
val wePlay = when (result) {
1 -> opponentPlays
2 -> (opponentPlays + 1) % 3
else -> if (opponentPlays == 0) 2 else opponentPlays - 1
}
scoreGame(opponentPlays, wePlay)
}
return scores.sum()
}
// 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 |
511fc33f9dded71937b6bfb55a675beace84ca22
| 1,714 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day12.kt
|
cagriyildirimR
| 572,811,424 | false |
{"Kotlin": 34697}
|
fun day12Part1() {
val input = readInput("Day12")
val visited = MutableList(input.size) { MutableList(input[0].length) { false } }
val dist = MutableList(input.size) { MutableList(input[0].length) { 999_999 } }
val prev = MutableList(input.size) { MutableList<Point?>(input[0].length) { null } }
// find Start point
var s = Point(0, 0)
var e = Point(0, 0)
for (rows in input.indices) {
for (i in input[rows].indices) {
if (input[rows][i] == 'S') {
s = Point(rows, i)
}
if (input[rows][i] == 'E') {
e = Point(rows, i)
}
}
}
fun movable(p: Point, q: Point): Boolean {
if (input[q.first][q.second] in 'a'..input[p.first][p.second] + 1) {
return true
}
if (input[p.first][p.second] == 'S') {
return true
}
if (input[q.first][q.second] == 'E' && input[p.first][p.second] == 'z') {
return true
}
return false
}
fun neighbours(p: Pair<Int, Int>): List<Pair<Int, Int>> {
val result = mutableListOf<Pair<Int, Int>>()
if (p.first > 0) result.add(Pair(p.first - 1, p.second)) // North
if (p.first < input.lastIndex) result.add(Pair(p.first + 1, p.second)) // South
if (p.second > 0) result.add(Pair(p.first, p.second - 1)) // West
if (p.second < input.first().lastIndex) result.add(Pair(p.first, p.second + 1)) // East
return result.filter { movable(p, it) && !visited[it.first][it.second] }
}
fun shortestUnvisited(): Point? {
var min: Point? = null
for (i in dist.indices) {
for (j in dist[i].indices) {
if (!visited[i][j] && (min == null || dist[i][j] < dist[min.first][min.second])) {
min = Point(i, j)
}
}
}
return min
}
fun getDist(p: Point): Int {
return dist[p.first][p.second]
}
var c = s
dist[c.first][c.second] = 0
do {
visited[c.first][c.second] = true
for (n in neighbours(c)) {
if (getDist(n) > getDist(c) + 1) {
dist[n.first][n.second] = dist[c.first][c.second] + 1
prev[n.first][n.second] = c
}
}
val x = shortestUnvisited()
if (x != null) {
c = x
}
} while (x != null)
println(dist[e.first][e.second])
}
typealias Point = Pair<Int, Int>
fun day12Part2() {
var input = readInput("Day12")
fun solve(t: Point): Int {
val visited = MutableList(input.size) { MutableList(input[0].length) { false } }
val dist = MutableList(input.size) { MutableList(input[0].length) { 999_999 } }
val prev = MutableList(input.size) { MutableList<Point?>(input[0].length) { null } }
// find Start point
var e = Point(0, 0)
for (rows in input.indices) {
for (i in input[rows].indices) {
if (input[rows][i] == 'E') {
e = Point(rows, i)
}
}
}
fun movable(p: Point, q: Point): Boolean {
if (input[q.first][q.second] in 'a'..input[p.first][p.second] + 1) {
return true
}
if (input[p.first][p.second] == 'S') {
return true
}
if (input[q.first][q.second] == 'E' && input[p.first][p.second] == 'z') {
return true
}
return false
}
fun neighbours(p: Pair<Int, Int>): List<Pair<Int, Int>> {
val result = mutableListOf<Pair<Int, Int>>()
if (p.first > 0) result.add(Pair(p.first - 1, p.second)) // North
if (p.first < input.lastIndex) result.add(Pair(p.first + 1, p.second)) // South
if (p.second > 0) result.add(Pair(p.first, p.second - 1)) // West
if (p.second < input.first().lastIndex) result.add(Pair(p.first, p.second + 1)) // East
return result.filter { movable(p, it) && !visited[it.first][it.second] }
}
fun shortestUnvisited(): Point? {
var min: Point? = null
for (i in dist.indices) {
for (j in dist[i].indices) {
if (!visited[i][j] && (min == null || dist[i][j] < dist[min.first][min.second])) {
min = Point(i, j)
}
}
}
return min
}
fun getDist(p: Point): Int {
return dist[p.first][p.second]
}
var c = t
dist[c.first][c.second] = 0
do {
visited[c.first][c.second] = true
for (n in neighbours(c)) {
if (getDist(n) > getDist(c) + 1) {
dist[n.first][n.second] = dist[c.first][c.second] + 1
prev[n.first][n.second] = c
}
}
val x = shortestUnvisited()
if (x != null) {
c = x
}
} while (x != null)
println(dist[e.first][e.second])
return dist[e.first][e.second]
}
val result = mutableListOf<Int>()
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == 'a') result.add(solve(Point(i, j)))
}
}
result.min().print()
}
| 0 |
Kotlin
| 0 | 0 |
343efa0fb8ee76b7b2530269bd986e6171d8bb68
| 5,417 |
AoC
|
Apache License 2.0
|
src/Day04.kt
|
MSchu160475
| 573,330,549 | false |
{"Kotlin": 5456}
|
fun main() {
fun part1(input: List<String>): Int {
return input.fold(0) { acc, cs ->
val sections = cs.split(",")
.map { section -> section.split("-").map { it.toInt() } }
.map { Pair(it[0], it[1]) }
.sortedByDescending { it.second - it.first }
if (sections[1].first in sections[0].first .. sections[0].second
&& sections[1].second in sections[0].first .. sections[0].second) acc + 1 else acc
}
}
fun part2(input: List<String>): Int {
return input.fold(0) { acc, cs ->
val sections = cs.split(",")
.map { section -> section.split("-").map { it.toInt() } }
.map { Pair(it[0], it[1]) }
.map { (it.first..it.second).toList().toIntArray() }
val intersectedArea = sections[0].intersect(sections[1].toSet())
if (intersectedArea.isNotEmpty()) acc + 1 else acc
}
}
// 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 |
c6f9a0892a28f0f03b95768b6611e520c85db75c
| 1,259 |
advent-of-code-2022-kotlin
|
Apache License 2.0
|
src/main/kotlin/day15/Day15.kt
|
TheSench
| 572,930,570 | false |
{"Kotlin": 128505}
|
package day15
import runDay
import utils.Point
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
var minX: Int = Int.MAX_VALUE
var maxX: Int = Int.MIN_VALUE
val y = 2000000
return input
.map { it.parse() }
.map {
minX = min(minX, it.xBounds.first)
maxX = max(maxX, it.xBounds.last)
it
}
.filter { y in it.yBounds }
.toList().sortedBy { it.xBounds.first }
.let {
val offsetX = max(0, 0 - minX)
it.fold(".".repeat(maxX - minX + 1).toCharArray()) { row, coords ->
val narrowing = abs(y - coords.sensor.y)
val coveredRange = (coords.xBounds.first + narrowing)..(coords.xBounds.last - narrowing)
coveredRange.fold(row) { row, x ->
val adjX = x + offsetX
row[adjX] = when (row[adjX]) {
'B' -> 'B'
else -> '#'
}
row
}.also {
if (coords.beacon.y == y) {
row[coords.beacon.x + offsetX] = 'B'
}
}
}
}.count { it == '#' }
}
fun part2(input: List<String>): Long {
var maxCoordX = 0
var maxCoordY = 0
return input
.map { it.parse() }
.map {
maxCoordX = max(maxCoordX, it.xBounds.last)
maxCoordY = max(maxCoordX, it.yBounds.last)
it
}
.toList()
.let found@{ row ->
val maxX = min(4000000, maxCoordX)
val maxY = min(4000000, maxCoordY)
(0..maxY).forEach { y ->
row.filter { y in it.yBounds }
.checkForBeacon(y, maxX)?.let {
return@found it
}
}
Point(0, 0)
}.let { (x, y) ->
x.toLong() * 4000000 + y.toLong()
}
}
(object {}).runDay(
part1 = ::part1,
part1Check = 0, // change to 26 to test output - test and actual check different rows
part2 = ::part2,
part2Check = 108000000L, // change to 56000011 to test output - test and actual check different rows
)
}
fun List<ParsedLine>.checkForBeacon(y: Int, maxX: Int): Point? {
this.map { coords ->
val narrowing = abs(y - coords.sensor.y)
(coords.xBounds.first + narrowing)..(coords.xBounds.last - narrowing)
}.sortedBy { it.first }
.let { ranges ->
val lastX = ranges.maxOf { it.last }
when {
(ranges.first().first > 0) -> return Point(0, y)
(lastX < maxX) -> return Point(lastX + 1, y)
else -> ranges
}
}.fold(0) { lastX, nextRange ->
if (nextRange.first > lastX + 1) {
return Point(lastX + 1, y)
}
max(lastX, nextRange.last)
}
return null
}
data class ParsedLine(val sensor: Point, val beacon: Point) {
private val manhattanDistance = sensor manhattanDistanceTo beacon
val xBounds = (sensor.x - manhattanDistance)..(sensor.x + manhattanDistance)
val yBounds = (sensor.y - manhattanDistance)..(sensor.y + manhattanDistance)
}
fun String.parse(): ParsedLine = split(": ", limit = 2).let {
ParsedLine(
it.first().toPoint(),
it.last().toPoint(),
)
}
val pointRegex = Regex("""x=(-?\d+), y=(-?\d+)""")
fun String.toPoint(): Point = pointRegex.find(this)!!
.destructured
.let { (x, y) -> Point(x.toInt(), y.toInt()) }
infix fun Point.manhattanDistanceTo(other: Point) =
(other - this).toAbsolute().run { x + y }
| 0 |
Kotlin
| 0 | 0 |
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
| 3,997 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day12.kt
|
RandomUserIK
| 572,624,698 | false |
{"Kotlin": 21278}
|
private const val START_SYMBOL = 'S'
private const val END_SYMBOL = 'E'
private class Heightmap(
val start: Point2D,
val end: Point2D,
val heights: Map<Point2D, Int>,
) {
fun shortestPath(from: Point2D, isGoal: (Point2D) -> Boolean, canMoveToward: (Int, Int) -> Boolean): Int {
val visited = mutableSetOf<Point2D>()
val steps = ArrayDeque<Step>().also { it.add(Step(from)) }
while (steps.isNotEmpty()) {
val currentStep = steps.removeFirst()
if (isGoal(currentStep.from))
return currentStep.distance
currentStep.from.adjacentPoints
.filter { it !in visited && it in heights }
.filter { to -> canMoveToward(heights.getValue(currentStep.from), heights.getValue(to)) }
.forEach {
steps.add(currentStep.toward(it))
visited.add(it)
}
}
throw IllegalStateException("Could not find the shortest path.")
}
}
private data class Point2D(
val x: Int,
val y: Int,
) {
val adjacentPoints: Set<Point2D>
get() =
setOf(
copy(x = x - 1, y = y),
copy(x = x + 1, y = y),
copy(x = x, y = y - 1),
copy(x = x, y = y + 1),
)
}
private data class Step(val from: Point2D, val distance: Int = 0) {
fun toward(other: Point2D) = copy(from = other, distance = distance + 1)
}
private fun List<String>.toHeightmap(): Heightmap {
var start: Point2D? = null
var end: Point2D? = null
val heights: MutableMap<Point2D, Int> = mutableMapOf()
mapIndexed { y, row ->
row.mapIndexed { x, c ->
val current = Point2D(x, y)
heights.put(
current,
when (c) {
START_SYMBOL -> 0.also { start = current }
END_SYMBOL -> 25.also { end = current }
else -> c - 'a'
}
)
}
}
requireNotNull(start) { "Starting point not found!" }
requireNotNull(end) { "End point not found!" }
return Heightmap(
start = start!!,
end = end!!,
heights = heights.toMap(),
)
}
fun main() {
fun part1(heightmap: Heightmap): Int =
heightmap.shortestPath(
from = heightmap.start,
isGoal = { it == heightmap.end },
canMoveToward = { from, to -> to - from <= 1 }
)
fun part2(heightmap: Heightmap): Int =
heightmap.shortestPath(
from = heightmap.end,
isGoal = { heightmap.heights[it] == 0 },
canMoveToward = { from, to -> from - to <= 1 }
)
val input = readInput("inputs/day12_input")
println(part1(input.toHeightmap()))
println(part2(input.toHeightmap()))
}
| 0 |
Kotlin
| 0 | 0 |
f22f10da922832d78dd444b5c9cc08fadc566b4b
| 2,359 |
advent-of-code-2022
|
Apache License 2.0
|
src/day19/Day19.kt
|
davidcurrie
| 579,636,994 | false |
{"Kotlin": 52697}
|
package day19
import java.io.File
import java.lang.IllegalStateException
import java.util.PriorityQueue
import kotlin.math.ceil
import kotlin.math.max
fun main() {
val regexp = Regex("\\d+")
val blueprints = File("src/day19/input.txt").readLines()
.map {
regexp.findAll(it).drop(1).map { it.value.toInt() }.toList().let { matches ->
listOf(
Quadruple(matches[0], 0, 0, 0),
Quadruple(matches[1], 0, 0, 0),
Quadruple(matches[2], matches[3], 0, 0),
Quadruple(matches[4], 0, matches[5], 0)
)
}
}
println(blueprints.map { maxGeodes(it, 24) }.mapIndexed { i, geodes -> (i + 1) * geodes }.sum())
println(blueprints.take(3).map { maxGeodes(it, 32) }.reduce(Int::times))
}
fun maxGeodes(blueprint: List<Quadruple>, totalMinutes: Int): Int {
var maxGeodes = 0
val queue = PriorityQueue<State>().apply { add(State(1, Quadruple(1, 0, 0, 0), Quadruple(1, 0, 0, 0))) }
while (queue.isNotEmpty()) {
val state = queue.poll()
maxGeodes = max(maxGeodes, state.materials.geode)
if (state.minute == totalMinutes) continue
val theoreticalMaxGeodes =
state.materials.geode + (state.minute..totalMinutes).sumOf { it + state.robots.geode }
if (theoreticalMaxGeodes > maxGeodes) {
queue.addAll(state.next(blueprint, totalMinutes))
}
}
return maxGeodes
}
data class Quadruple(val ore: Int, val clay: Int, val obsidian: Int, val geode: Int) {
operator fun plus(other: Quadruple) =
Quadruple(ore + other.ore, clay + other.clay, obsidian + other.obsidian, geode + other.geode)
operator fun minus(other: Quadruple) =
Quadruple(ore - other.ore, clay - other.clay, obsidian - other.obsidian, geode - other.geode)
operator fun times(multiple: Int) =
Quadruple(ore * multiple, clay * multiple, obsidian * multiple, geode * multiple)
fun timeToBuild(required: Quadruple): Int = maxOf(
if (required.ore <= 0) 0 else ceil(required.ore.toDouble() / ore).toInt(),
if (required.clay <= 0) 0 else ceil(required.clay.toDouble() / clay).toInt(),
if (required.obsidian <= 0) 0 else ceil(required.obsidian.toDouble() / obsidian).toInt(),
if (required.geode <= 0) 0 else ceil(required.geode.toDouble() / geode).toInt()
) + 1
companion object {
fun of(index: Int) =
when (index) {
0 -> Quadruple(1, 0, 0, 0)
1 -> Quadruple(0, 1, 0, 0)
2 -> Quadruple(0, 0, 1, 0)
3 -> Quadruple(0, 0, 0, 1)
else -> throw IllegalStateException()
}
}
}
data class State(val minute: Int, val robots: Quadruple, val materials: Quadruple) : Comparable<State> {
fun next(blueprint: List<Quadruple>, totalMinutes: Int): List<State> {
val nextBuildStates = mutableListOf<State>()
if (blueprint.maxOf { it.ore } > robots.ore && materials.ore > 0) {
nextBuildStates += nextForRobot(blueprint, 0)
}
if (blueprint.maxOf { it.clay } > robots.clay && materials.ore > 0) {
nextBuildStates += nextForRobot(blueprint, 1)
}
if (blueprint.maxOf { it.obsidian } > robots.obsidian && materials.ore > 0 && materials.clay > 0) {
nextBuildStates += nextForRobot(blueprint, 2)
}
if (materials.ore > 0 && materials.obsidian > 0) {
nextBuildStates += nextForRobot(blueprint, 3)
}
val nextBuildStatesWithinTime = nextBuildStates.filter { it.minute <= totalMinutes }.toMutableList()
return nextBuildStatesWithinTime.ifEmpty { listOf(State(totalMinutes, robots, materials + (robots * (totalMinutes - minute)))) }
}
private fun nextForRobot(blueprint: List<Quadruple>, index: Int): State {
return robots.timeToBuild(blueprint[index] - materials)
.let { time ->
State(
minute + time,
robots + Quadruple.of(index),
materials - blueprint[index] + (robots * time)
)
}
}
override fun compareTo(other: State) = other.materials.geode.compareTo(materials.geode)
}
| 0 |
Kotlin
| 0 | 0 |
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
| 4,310 |
advent-of-code-2022
|
MIT License
|
src/Day08.kt
|
Venkat-juju
| 572,834,602 | false |
{"Kotlin": 27944}
|
import kotlin.math.max
//1825
//235200
fun main() {
fun isVisible(treeIndex: Int, treeLine: List<Int>): Boolean {
val treeHeight = treeLine[treeIndex]
return treeLine.slice(0 until treeIndex).all{it < treeHeight} || treeLine.slice(treeIndex + 1 .. treeLine.lastIndex).all{it < treeHeight}
}
fun lineScenicScore(treeIndex: Int, treeLine: List<Int>): Int {
val leftTrees = treeLine.slice(treeIndex - 1 downTo 0)
val rightTrees = treeLine.slice(treeIndex + 1 .. treeLine.lastIndex)
val treeHeight = treeLine[treeIndex]
var leftVisibleTrees = leftTrees.indexOfFirst { it >= treeHeight } + 1
var rightVisibleTrees = rightTrees.indexOfFirst { it >= treeHeight } + 1
if (leftVisibleTrees == 0) leftVisibleTrees = leftTrees.size
if (rightVisibleTrees == 0) rightVisibleTrees = rightTrees.size
return leftVisibleTrees * rightVisibleTrees
}
fun part1(input: List<String>): Int {
val treeGrid = mutableListOf<List<Int>>()
input.forEach {
treeGrid.add(it.split("").filterNot(String::isBlank).map(String::toInt))
}
var numberOfVisibleTrees = (2 * treeGrid.size + 2 * treeGrid.first().size) - 4
for(i in 1 until treeGrid.lastIndex) {
for(j in 1 until treeGrid[i].lastIndex) {
if (isVisible(j, treeGrid[i]) || isVisible(i, treeGrid.map { it[j] })) {
numberOfVisibleTrees++
}
}
}
return numberOfVisibleTrees
}
fun part2(input: List<String>): Int {
val treeGrid = mutableListOf<List<Int>>()
input.forEach {
treeGrid.add(it.split("").filterNot(String::isBlank).map(String::toInt))
}
var maxScenicScore = 0
for(i in 1 until treeGrid.lastIndex) {
for(j in 1 until treeGrid[i].lastIndex) {
val currentTreeScenicScore = lineScenicScore(j, treeGrid[i]) * lineScenicScore(i, treeGrid.map { it[j] })
maxScenicScore = max(currentTreeScenicScore, maxScenicScore)
}
}
return maxScenicScore
}
// 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 |
785a737b3dd0d2259ccdcc7de1bb705e302b298f
| 2,434 |
aoc-2022
|
Apache License 2.0
|
src/Day02.kt
|
xabgesagtx
| 572,139,500 | false |
{"Kotlin": 23192}
|
import Result.*
import Sign.*
fun main() {
fun part1(input: List<String>): Int {
return input.map {
it.split(" ")
}.map { it[0].asSign() to it[1].asSign() }
.sumOf { score(it.first, it.second) }
}
fun part2(input: List<String>): Int {
return input.map {
it.split(" ")
}.map { it[0].asSign() to it[1].asResult() }
.sumOf { score(it.first, it.second) }
}
// 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))
}
private fun score(first: Sign, second: Sign): Int =
when {
first == second -> DRAW.points + second.points
first.beats(second) -> LOSS.points + second.points
else -> WIN.points + second.points
}
private fun score(sign: Sign, result: Result) = result.matchingSign(sign).points + result.points
private val winMap = mapOf(
ROCK to SCISSORS,
PAPER to ROCK,
SCISSORS to PAPER
)
private val lossMap = winMap.entries.associate { it.value to it.key }
private enum class Sign(val points: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
fun beats(other: Sign): Boolean {
return winMap[this] == other
}
}
private enum class Result(val points: Int) {
LOSS(0), WIN(6), DRAW(3);
fun matchingSign(other: Sign): Sign {
return when(this) {
DRAW -> other
LOSS -> winMap[other]!!
WIN -> lossMap[other]!!
}
}
}
private fun String.asSign(): Sign {
return when (this) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException()
}
}
private fun String.asResult(): Result {
return when (this) {
"X" -> LOSS
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException()
}
}
| 0 |
Kotlin
| 0 | 0 |
976d56bd723a7fc712074066949e03a770219b10
| 2,026 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day12.kt
|
zsmb13
| 572,719,881 | false |
{"Kotlin": 32865}
|
fun main() {
fun bfs(testInput: List<String>, sy: Int, sx: Int): Int {
val input = testInput.map { it.replace('S', 'a').replace('E', 'z') }
val dist = Array(input.size) { IntArray(input.first().length) { 100000 } }
dist[sy][sx] = 0
val visited = mutableSetOf<Pair<Int, Int>>()
val toVisit = mutableListOf(sy to sx)
val nOffsets = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1)
while (toVisit.isNotEmpty()) {
val (y, x) = toVisit.removeFirst()
nOffsets
.map { (dy, dx) -> (y + dy) to (x + dx) }
.forEach { (ny, nx) ->
val neighbor = input.getOrNull(ny)?.getOrNull(nx) ?: return@forEach
if (neighbor - input[y][x] <= 1) {
dist[ny][nx] = minOf(dist[ny][nx], dist[y][x] + 1)
if ((ny to nx) !in visited && (ny to nx) !in toVisit) {
toVisit += (ny to nx)
}
}
}
visited += (y to x)
}
val ty = testInput.indexOfFirst { it.contains('E') }
val tx = testInput[ty].indexOf('E')
return dist[ty][tx]
}
fun part1(testInput: List<String>): Int {
val sy = testInput.indexOfFirst { it.contains('S') }
val sx = testInput[sy].indexOf('S')
return bfs(testInput = testInput, sy = sy, sx = sx)
}
fun part2(testInput: List<String>): Int {
return testInput.indices.minOf { index ->
bfs(testInput = testInput, sy = index, sx = 0)
}
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
check(part1(input).also(::println) == 504)
check(part2(input).also(::println) == 500)
}
| 0 |
Kotlin
| 0 | 6 |
32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35
| 1,864 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day19.kt
|
er453r
| 572,440,270 | false |
{"Kotlin": 69456}
|
import java.lang.Integer.max
fun main() {
fun part1(input: List<String>): Int {
val blueprints = input.map { line ->
line.ints().let {
listOf(
VectorN(it[1], 0, 0, 0),
VectorN(it[2], 0, 0, 0),
VectorN(it[3], it[4], 0, 0),
VectorN(it[5], 0, it[6], 0),
)
}
}
val timeLimit = 24
var bestForMinute = Array<Int>(30) { 0 }
fun decision(budget: VectorN, robots: VectorN, minutes: Int, blueprint: List<VectorN>, maxBudget: VectorN, robotsWeDidNotBuild:Set<Int> = emptySet()): Int {
if (minutes > timeLimit) { // end condition
return budget.components[3]
}
// pruning
if (budget.components[3] > bestForMinute[minutes])
bestForMinute[minutes] = budget.components[3]
if (bestForMinute[minutes] > budget.components[3])
return budget.components[3]
// robots we can afford
val robotsWeCanAfford = blueprint.mapIndexed { index, it -> index to ((budget - it).components.min() >= 0) }.filter { (_, canAfford) -> canAfford }.map { it.first }.toSet()
// we need to buy geode if we can afford it
if (robotsWeCanAfford.contains(3))
return decision(budget + robots - blueprint[3], robots + VectorN(0, 0, 0, 1), minutes + 1, blueprint, maxBudget)
val robotsItMakesSenseToMake = robotsWeCanAfford.filter { robotIndex ->
when{
robotIndex in robotsWeDidNotBuild -> false
(robots.components[robotIndex] >= maxBudget.components[robotIndex]) -> false
else -> true
}
}.toSet()
val withoutBuilding = decision(budget + robots, robots, minutes + 1, blueprint, maxBudget, robotsItMakesSenseToMake)
if (robotsItMakesSenseToMake.isNotEmpty()) {
val withBuilding = robotsItMakesSenseToMake.maxOf { robotIndex ->
decision(budget + robots - blueprint[robotIndex], robots + VectorN(0, 0, 0, 0).also { it.components[robotIndex] = 1 }, minutes + 1, blueprint, maxBudget)
}
return max(withBuilding, withoutBuilding)
}
return withoutBuilding
}
return blueprints.mapIndexed { index, blueprint ->
bestForMinute = Array<Int>(30) { 0 }
val budget = VectorN(0, 0, 0, 0) // ore, clay, obsidian, geode
val robots = VectorN(1, 0, 0, 0)
val maxBudget = VectorN((0..3).map { c -> blueprint.maxOf { it.components[c] } }.toMutableList())
println("maxBudget $maxBudget")
val maxGeodes = decision(budget, robots, 1, blueprint, maxBudget)
println("Blueprint $index produces max $maxGeodes geodes")
(index + 1) * maxGeodes
}.sum()
}
fun part2(input: List<String>): Int {
val blueprints = input.map { line ->
line.ints().let {
listOf(
VectorN(it[1], 0, 0, 0),
VectorN(it[2], 0, 0, 0),
VectorN(it[3], it[4], 0, 0),
VectorN(it[5], 0, it[6], 0),
)
}
}.take(3)
val timeLimit = 32
var bestForMinute = Array<Int>(33) { 0 }
fun decision(budget: VectorN, robots: VectorN, minutes: Int, blueprint: List<VectorN>, maxBudget: VectorN, robotsWeDidNotBuild:Set<Int> = emptySet()): Int {
if (minutes > timeLimit) { // end condition
return budget.components[3]
}
// pruning
if (budget.components[3] > bestForMinute[minutes])
bestForMinute[minutes] = budget.components[3]
if (bestForMinute[minutes] > budget.components[3])
return budget.components[3]
// robots we can afford
val robotsWeCanAfford = blueprint.mapIndexed { index, it -> index to ((budget - it).components.min() >= 0) }.filter { (_, canAfford) -> canAfford }.map { it.first }.toSet()
// we need to buy geode if we can afford it
if (robotsWeCanAfford.contains(3))
return decision(budget + robots - blueprint[3], robots + VectorN(0, 0, 0, 1), minutes + 1, blueprint, maxBudget)
val robotsItMakesSenseToMake = robotsWeCanAfford.filter { robotIndex ->
when{
robotIndex in robotsWeDidNotBuild -> false
(robots.components[robotIndex] >= maxBudget.components[robotIndex]) -> false
else -> true
}
}.toSet()
val withoutBuilding = decision(budget + robots, robots, minutes + 1, blueprint, maxBudget, robotsItMakesSenseToMake)
if (robotsItMakesSenseToMake.isNotEmpty()) {
val withBuilding = robotsItMakesSenseToMake.maxOf { robotIndex ->
decision(budget + robots - blueprint[robotIndex], robots + VectorN(0, 0, 0, 0).also { it.components[robotIndex] = 1 }, minutes + 1, blueprint, maxBudget)
}
return max(withBuilding, withoutBuilding)
}
return withoutBuilding
}
return blueprints.mapIndexed { index, blueprint ->
bestForMinute = Array<Int>(33) { 0 }
val budget = VectorN(0, 0, 0, 0) // ore, clay, obsidian, geode
val robots = VectorN(1, 0, 0, 0)
val maxBudget = VectorN((0..3).map { c -> blueprint.maxOf { it.components[c] } }.toMutableList())
println("maxBudget $maxBudget")
val maxGeodes = decision(budget, robots, 1, blueprint, maxBudget)
println("Blueprint $index produces max $maxGeodes geodes")
maxGeodes
}.reduce(Int::times)
}
test(
day = 19,
testTarget1 = 33,
testTarget2 = 3472, // 56 * 62
part1 = ::part1,
part2 = ::part2,
)
}
| 0 |
Kotlin
| 0 | 0 |
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
| 6,117 |
aoc2022
|
Apache License 2.0
|
src/Day15.kt
|
wgolyakov
| 572,463,468 | false | null |
import kotlin.math.absoluteValue
fun main() {
fun distance(p1: Pair<Int, Int>, p2: Pair<Int, Int>) =
(p1.first - p2.first).absoluteValue + (p1.second - p2.second).absoluteValue
fun parse(input: List<String>): Triple<List<Pair<Int, Int>>, Set<Pair<Int, Int>>, List<Int>> {
val sensors = mutableListOf<Pair<Int, Int>>()
val beacons = mutableSetOf<Pair<Int, Int>>()
val closestDist = mutableListOf<Int>()
for (line in input) {
val (sensorX, sensorY, beaconX, beaconY) =
Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
.matchEntire(line)!!.groupValues.takeLast(4).map { it.toInt() }
sensors.add(sensorX to sensorY)
beacons.add(beaconX to beaconY)
closestDist.add(distance(sensorX to sensorY, beaconX to beaconY))
}
return Triple(sensors, beacons, closestDist)
}
fun part1(input: List<String>, y: Int): Int {
val (sensors, beacons, closestDist) = parse(input)
val noBeaconX = mutableSetOf<Int>()
for (i in sensors.indices) {
val sensor = sensors[i]
val d = closestDist[i]
var x = sensor.first
while (distance(x to y, sensor) <= d) {
if (x to y !in beacons) noBeaconX.add(x)
x++
}
x = sensor.first - 1
while (distance(x to y, sensor) <= d) {
if (x to y !in beacons) noBeaconX.add(x)
x--
}
}
return noBeaconX.size
}
fun part2(input: List<String>, limit: Int): Long {
val (sensors, _, closestDist) = parse(input)
fun isDistress(x: Int, y: Int) = sensors.indices.all { distance(x to y, sensors[it]) > closestDist[it] }
for (i in sensors.indices) {
val (x0, y0) = sensors[i]
val r = closestDist[i]
var y: Int
for (x in 0..limit) {
y = x + y0 - x0 - r - 1
if (y in 0..limit && isDistress(x, y))
return x.toLong() * 4000000 + y
y = x + y0 - x0 + r + 1
if (y in 0..limit && isDistress(x, y))
return x.toLong() * 4000000 + y
y = -x + y0 + x0 - r - 1
if (y in 0..limit && isDistress(x, y))
return x.toLong() * 4000000 + y
y = -x + y0 + x0 + r + 1
if (y in 0..limit && isDistress(x, y))
return x.toLong() * 4000000 + y
}
}
return -1
}
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 4000000))
}
| 0 |
Kotlin
| 0 | 0 |
789a2a027ea57954301d7267a14e26e39bfbc3c7
| 2,349 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/mkuhn/aoc/Day12.kt
|
mtkuhn
| 572,236,871 | false |
{"Kotlin": 53161}
|
package mkuhn.aoc
import mkuhn.aoc.util.Grid
import mkuhn.aoc.util.Point
import mkuhn.aoc.util.readInput
import mkuhn.aoc.util.transpose
fun main() {
val input = readInput("Day12")
println(day12part1(input))
println(day12part2(input))
}
fun day12part1(input: List<String>): Int =
(ElevationGrid(input.map { it.toList() }.transpose()).findShortestPath()?.size?:Int.MAX_VALUE)-1
fun day12part2(input: List<String>): Int {
val grid = ElevationGrid(input.map { it.toList() }.transpose())
return grid.allPoints()
.filter { grid.height(it) == 0 }
.map { grid.findShortestPath(fromPoint = it) }
.minOf { it?.size?:Int.MAX_VALUE }-1
}
data class GraphNode(val currPos: Point, val visited: List<Point>)
class ElevationGrid(g: List<List<Char>>): Grid<Char>(g) {
fun height(pos: Point): Int =
when {
valueAt(pos) == 'S' -> 'a'.code
valueAt(pos) == 'E' -> 'z'.code
else -> valueAt(pos).code
} - 'a'.code
fun findShortestPath(
fromPoint: Point = allPoints().first { valueAt(it) == 'S' },
toPoint: Point = allPoints().first { valueAt(it) == 'E' }
): List<Point>? {
val root = GraphNode(fromPoint, listOf(fromPoint))
var nodes = mutableListOf(root)
val evaluatedPoints = mutableMapOf<Point, Int>()
while (nodes.isNotEmpty() && !nodes.any { it.currPos == toPoint }) {
//pop off our favorite node via A* search
val best = nodes.minBy { it.visited.size + ('z'.code-height(it.currPos)) }
nodes.remove(best)
//println("nodes=${nodes.size}, eval ${best.currPos}, size ${best.visited.size} | ${best.visited}")
//let's track points we've seen before, and keep only the most efficient nodes at that point
if((evaluatedPoints[best.currPos]?:Int.MAX_VALUE) > best.visited.size) {
evaluatedPoints[best.currPos] = best.visited.size
nodes = nodes.filter { (evaluatedPoints[it.currPos]?:Int.MAX_VALUE) > it.visited.size }.toMutableList()
}
//expand to adjacent nodes and filter out bad choices
nodes += cardinalAdjacentTo(best.currPos)
.filter { height(it) <= height(best.currPos)+1 } //can't climb more than 1 height
.filter { (evaluatedPoints[it]?:Int.MAX_VALUE) > best.visited.size+1 } //make sure we're not covering ground that we already did more efficiently
.filter { it !in best.visited } //no looping around
.map { p -> GraphNode(p, best.visited + p) }
}
return nodes.firstOrNull { it.currPos == toPoint }?.visited
}
}
| 0 |
Kotlin
| 0 | 1 |
89138e33bb269f8e0ef99a4be2c029065b69bc5c
| 2,694 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day16.kt
|
jorgecastrejon
| 573,097,701 | false |
{"Kotlin": 33669}
|
import java.util.*
fun main() {
fun part1(input: List<String>): Int {
val start = "AA"
val maxTime = 30
val (rates, tunnels) = parseInput(input)
val options = rates.filter { (name, rate) -> name == start || rate > 0 }
.map { (name, _) -> name to calculateOptions(name, rates, tunnels) }
.toMap()
val finished = mutableListOf<Solution>()
val solutions = LinkedList<Solution>().apply { add(Solution(latest = start)) }
while (solutions.isNotEmpty()) {
val solution = solutions.removeLast()
options[solution.latest]?.forEach { (next, distance) ->
val moveTime = solution.time + distance + 1
if (moveTime < maxTime && !solution.valves.contains(next)) {
val valveFinalPressure = (maxTime - moveTime) * rates.getOrDefault(next, 0)
solutions.add(
Solution(
pressure = solution.pressure + valveFinalPressure,
time = moveTime,
latest = next,
valves = solution.valves + next
)
)
} else if (solution.valves.size == options.keys.size || moveTime > maxTime) {
finished.add(solution)
}
}
}
return finished.maxBy(Solution::pressure).pressure
}
fun part2(input: List<String>): Int {
return 0
}
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
private fun calculateOptions(
start: String,
rates: Map<String, Int>,
tunnels: Map<String, List<String>>
): List<Pair<String, Int>> {
val result = mutableListOf<Pair<String, Int>>()
val visited = mutableSetOf(start)
val queue = LinkedList<Pair<String, Int>>()
queue.add(start to 0)
while (queue.isNotEmpty()) {
val (current, distance) = queue.removeLast()
tunnels[current]
?.filter { it !in visited }
?.forEach { next ->
visited.add(next)
if (rates.getOrDefault(next, 0) > 0) {
result.add(next to distance + 1)
}
queue.push(next to distance + 1)
}
}
return result
}
private fun parseInput(input: List<String>): Pair<Map<String, Int>, Map<String, List<String>>> {
val rates = mutableMapOf<String, Int>()
val tunnels = mutableMapOf<String, List<String>>()
input.forEach { line ->
val valve = line.split(" ", limit = 3)[1]
val rate = line.filter(Char::isDigit).toInt()
val flows = line.split(" to ").last().split(" ", limit = 2).last().split(", ")
rates[valve] = rate
tunnels[valve] = flows
}
return rates to tunnels
}
data class Solution(
val pressure: Int = 0,
val time: Int = 0,
val latest: String,
val valves: Set<String> = setOf(latest)
)
| 0 |
Kotlin
| 0 | 0 |
d83b6cea997bd18956141fa10e9188a82c138035
| 3,036 |
aoc-2022
|
Apache License 2.0
|
src/Day12.kt
|
wooodenleg
| 572,658,318 | false |
{"Kotlin": 30668}
|
fun List<IntOffset>.getNextSteps(
heightMap: Map<IntOffset, Char>,
wayUp: Boolean
): List<List<IntOffset>> {
val route = this
val currentPosition = route.last()
val currentHeight = heightMap[currentPosition]!!
val possibleDirections = Direction.values()
.map { currentPosition + it }
.filterNot(route::contains)
.filter(heightMap.keys::contains)
val nextSteps = buildList {
for (point in possibleDirections) {
val pointHeight = heightMap[point]!!
if (wayUp && pointHeight - 1 > currentHeight) continue
if (!wayUp && pointHeight < currentHeight - 1) continue
add(route + point)
}
}
return nextSteps
}
private fun parseHeightMap(input: List<String>): Map<IntOffset, Char> = buildMap {
input.forEachIndexed { y, row ->
row.forEachIndexed { x, heightMark ->
this[IntOffset(x, y)] = heightMark
}
}
}
private fun findShortestPaths(
map: Map<IntOffset, Char>,
wayUp: Boolean,
startPosition: IntOffset,
isEndPosition: (IntOffset) -> Boolean,
): Map<IntOffset, List<IntOffset>> {
val bestPathMap = mutableMapOf(startPosition to listOf(startPosition))
var changed: Int
do {
changed = 0
for (point in bestPathMap.keys.toList()) {
if (isEndPosition(point))
continue
val nextSteps = bestPathMap[point]?.getNextSteps(map, wayUp)
if (nextSteps.isNullOrEmpty()) continue
nextSteps.forEach { path ->
val bestPathSoFar = bestPathMap[path.last()]
fun savePath() {
bestPathMap[path.last()] = path
changed++
}
if (bestPathSoFar == null) savePath()
else if (path.size < bestPathSoFar.size) savePath()
}
}
} while (changed > 0)
return bestPathMap
}
fun main() {
fun part1(input: List<String>): Int {
val map = parseHeightMap(input)
val startPosition = map.entries.first { it.value == 'S' }.key
val endPosition = map.entries.first { it.value == 'E' }.key
val normalizedMap = map.mapValues {
when (it.value) {
'S' -> 'a'
'E' -> 'z'
else -> it.value
}
}
val bestPathMap = findShortestPaths(
map = normalizedMap,
wayUp = true,
startPosition = startPosition,
isEndPosition = { it == endPosition },
)
val shortestPath = bestPathMap[endPosition] ?: error("No path to end found")
return shortestPath.size - 1 // don't count first point
}
fun part2(input: List<String>): Int {
val map = parseHeightMap(input)
val startPosition = map.entries.first { it.value == 'E' }.key
val normalizedMap = map.mapValues {
when (it.value) {
'S' -> 'a'
'E' -> 'z'
else -> it.value
}
}
val bestPathMap = findShortestPaths(
map = normalizedMap,
wayUp = false,
startPosition = startPosition,
isEndPosition = { normalizedMap[it] == 'a' },
)
val shortestPath = bestPathMap.values
.filter { normalizedMap[it.last()] == 'a' }
.minBy(List<IntOffset>::size)
return shortestPath.size - 1 // don't count first point
}
val testInput = readInputLines("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInputLines("Day12")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
ff1f3198f42d1880e067e97f884c66c515c8eb87
| 3,718 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day19.kt
|
kpilyugin
| 572,573,503 | false |
{"Kotlin": 60569}
|
import kotlin.collections.HashSet
fun main() {
data class Resources(val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0) :
Comparable<Resources> {
fun isAtLeast(other: Resources) =
ore >= other.ore && clay >= other.clay && obsidian >= other.obsidian && geode >= other.geode
operator fun minus(other: Resources) =
Resources(ore - other.ore, clay - other.clay, obsidian - other.obsidian, geode - other.geode)
operator fun plus(other: Resources) =
Resources(ore + other.ore, clay + other.clay, obsidian + other.obsidian, geode + other.geode)
operator fun times(count: Int) =
Resources(ore * count, clay * count, obsidian * count, geode * count)
override fun compareTo(other: Resources) =
compareValuesBy(this, other, { it.geode }, { it.obsidian }, { it.clay }, { it.ore })
override fun toString() = listOf(ore, clay, obsidian, geode).joinToString()
}
fun solve(blueprint: String, minutes: Int): Int {
val parts = blueprint.split(':', '.')
val orePrice = parts[1].extractNumbers().let { Resources(ore = it[0]) }
val clayPrice = parts[2].extractNumbers().let { Resources(ore = it[0]) }
val obsidianPrice = parts[3].extractNumbers().let { Resources(ore = it[0], clay = it[1]) }
val geodePrice = parts[4].extractNumbers().let { Resources(ore = it[0], obsidian = it[1]) }
data class State(val robots: Resources, val resources: Resources) : Comparable<State> {
fun next(): List<State> = buildList {
val resourcesAfter = resources + robots
for ((price, newRobot) in listOf(
geodePrice to Resources(geode = 1),
obsidianPrice to Resources(obsidian = 1),
clayPrice to Resources(clay = 1),
orePrice to Resources(ore = 1)
)) {
if (resources.isAtLeast(price)) {
add(State(robots + newRobot, resourcesAfter - price))
}
}
add(State(robots, resourcesAfter))
}
fun isBetter(other: State) =
other != this && robots.isAtLeast(other.robots) && resources.isAtLeast(other.resources)
override fun compareTo(other: State) = compareValuesBy(this, other, { it.resources }, { it.robots })
}
var states: List<State> = listOf(State(Resources(ore = 1), Resources()))
repeat(minutes) { minute ->
val newStatesSet = states.flatMapTo(HashSet()) { it.next() }
val sorted = newStatesSet.toList().sortedDescending().take(100000)
val prev = mutableListOf<State>()
val iter = sorted.iterator()
val newStates = mutableListOf<State>()
while (iter.hasNext()) {
val cur = iter.next()
if (!prev.any { it.isBetter(cur) }) {
prev += cur
if (prev.size > 5) prev.removeAt(0)
newStates += cur
}
}
states = newStates
}
val geodes = states.maxOf { it.resources.geode }
return geodes
}
fun part1(input: List<String>) =
input.withIndex().sumOf { line ->
((line.index + 1) * solve(line.value, 24)).also { println(it) }
}
fun part2(input: List<String>) = input.take(3).map { line -> solve(line, 32) }
val testInput = readInputLines("Day19_test")
check(part1(testInput), 33)
check(part2(testInput), listOf(56, 62))
val input = readInputLines("Day19")
println(part1(input))
val res2 = part2(input)
println("$res2: ${res2[0] * res2[1] * res2[2]}")
}
| 0 |
Kotlin
| 0 | 1 |
7f0cfc410c76b834a15275a7f6a164d887b2c316
| 3,820 |
Advent-of-Code-2022
|
Apache License 2.0
|
src/2022/Day03.kt
|
bartee
| 575,357,037 | false |
{"Kotlin": 26727}
|
fun main() {
val interpreter = Day03()
fun testGetCharacterPriority(){
val testArray = mapOf("a" to 1, "b" to 2, "f" to 6, "A" to 27, "B" to 28, "F" to 32, "Z" to 52)
for (entry in testArray.entries.iterator()) {
val test = interpreter.getCharacterPriority(entry.key)
check(test == entry.value)
}
}
fun testSplitIntoCompartments(){
val rucksackItems = arrayOf("abfdcABDCf", "poiuytrewqQWERTYUIOP")
for (entry in rucksackItems.iterator()){
interpreter.splitIntoCompartments(entry)
}
}
fun testDuplicates() {
val rucksackItems = mapOf("abfdcABDCf" to 1, "poiuytrewqQWERTYuiOP" to 2, "ASDFasdf" to 0)
for ((entry, counter) in rucksackItems.iterator()){
val compartments = interpreter.splitIntoCompartments(entry)
val res = interpreter.getDuplicates(compartments[0], compartments[1])
check(res.length == counter)
}
}
fun calculatePriorityOfDuplicates(input: List<String>): Int {
var score = 0
input.map {
val compartments = interpreter.splitIntoCompartments(it)
val duplicates = interpreter.getDuplicates(compartments[0], compartments[1])
var linescore = 0
for (el in duplicates.iterator()){
linescore += interpreter.getCharacterPriority(el.toString())
}
score += linescore
}
return score
}
fun checkGroupBadges(input: List<String>): Int {
var score = 0
// Divide all the rucksacks in groups of three
val groupRucksacks = input.chunked(3)
groupRucksacks.map {
// Let's make every rucksack distinct first
val rucksack1 = it[0].toCharArray().distinct()
val rucksack2 = it[1].toCharArray().distinct()
val rucksack3 = it[2].toCharArray().distinct()
for (el_1 in rucksack1){
var shared = false
for (el_2 in rucksack2) {
if (el_1 == el_2 && rucksack3.contains(el_1)){
// Element is in all three!
shared = true
}
}
if (shared) {
// Score it
val itemscore = interpreter.getCharacterPriority(el_1.toString())
score += itemscore
}
}
}
return score
}
// test if implementation meets criteria from the description, like:
testGetCharacterPriority()
testSplitIntoCompartments()
testDuplicates()
val testInput = readInput("resources/day03_example")
check(calculatePriorityOfDuplicates(testInput) == 157)
check(checkGroupBadges(testInput) == 70)
val realInput = readInput("resources/day03_dataset")
val realResult = calculatePriorityOfDuplicates(realInput)
val realBadgesResult = checkGroupBadges(realInput)
println("Total priorities: $realResult")
println("Priorities of badges per group of three elves: $realBadgesResult")
}
class Day03 {
fun getCharacterPriority(str: String): Int {
val toCheck = str.first()
if (toCheck.isUpperCase()){
return toCheck.code - 38
}
return toCheck.code - 96
}
fun splitIntoCompartments(str: String): Array<String> {
val firstCompartment = str.subSequence(0, str.length/2).toString()
val secondCompartment = str.subSequence(str.length/2, str.length).toString()
return arrayOf(firstCompartment, secondCompartment)
}
fun getDuplicates(firstCompartment: String, secondCompartment: String): String {
val duplicateList: MutableList<Char> = mutableListOf()
for (element in firstCompartment.iterator()){
if (secondCompartment.contains(element)) {
duplicateList.add(element)
}
}
return duplicateList.distinct().joinToString("")
}
}
| 0 |
Kotlin
| 0 | 0 |
c7141d10deffe35675a8ca43297460a4cc16abba
| 3,585 |
adventofcode2022
|
Apache License 2.0
|
src/main/kotlin/aoc2023/Day23.kt
|
Ceridan
| 725,711,266 | false |
{"Kotlin": 110767, "Shell": 1955}
|
package aoc2023
import kotlin.math.max
class Day23 {
fun part1(input: String): Int {
val (grid, start, end) = parseInput(input)
val graph = grid.convertToGraph().compactGraph()
return dfs(graph, start, end)
}
fun part2(input: String): Int {
val (grid, start, end) = parseInput(input)
val graph = grid
.mapValues { (_, ch) -> if (ch in ">v<^") '.' else ch }
.convertToGraph()
.compactGraph()
return dfs(graph, start, end)
}
private fun dfs(
graph: Map<Point, List<Edge>>,
current: Point,
end: Point,
steps: Int = 0,
visited: MutableSet<Point> = mutableSetOf()
): Int {
if (current == end) return steps
if (current in visited) return 0
var longestPath = 0
visited.add(current)
for (edge in graph[current]!!) {
longestPath = max(longestPath, dfs(graph, edge.v2, end, steps + edge.weight, visited))
}
visited.remove(current)
return longestPath
}
private fun Map<Point, Char>.convertToGraph(): Map<Point, List<Edge>> {
val graph = mutableMapOf<Point, List<Edge>>()
for ((point, ch) in this) {
if (ch == '#') continue
val edges = mutableListOf<Edge>()
val directions = when (ch) {
'>' -> listOf(Point(0, 1))
'v' -> listOf(Point(1, 0))
'<' -> listOf(Point(0, -1))
'^' -> listOf(Point(-1, 0))
else -> listOf(Point(-1, 0), Point(0, 1), Point(1, 0), Point(0, -1))
}
for (direction in directions) {
val adj = point + direction
if (this.getOrDefault(adj, '#') == '#') continue
edges.add(Edge(point, adj))
}
graph[point] = edges
}
return graph
}
private fun Map<Point, List<Edge>>.compactGraph(): Map<Point, List<Edge>> {
val newGraph = this.toMutableMap()
for (point in this.keys) {
val edges = newGraph[point]!!
if (edges.size != 2) continue
val (_, p0, w0) = edges[0]
val (_, p1, w1) = edges[1]
val prevW0 = newGraph[p0]!!.firstOrNull { it.v2 == p1 }?.weight ?: 0
val prevW1 = newGraph[p1]!!.firstOrNull { it.v2 == p0 }?.weight ?: 0
val newEdge0 = Edge(p0, p1, max(w0 + w1, prevW0))
val newEdge1 = Edge(p1, p0, max(w0 + w1, prevW1))
newGraph[p0] = newGraph[p0]!!.filter { it.v2 != point && it.v2 != p1 } + listOf(newEdge0)
newGraph[p1] = newGraph[p1]!!.filter { it.v2 != point && it.v2 != p0 } + listOf(newEdge1)
newGraph.remove(point)
}
return newGraph
}
private fun parseInput(input: String): Triple<Map<Point, Char>, Point, Point> {
val lines = input.split('\n').filter { it.isNotEmpty() }
val grid = mutableMapOf<Point, Char>()
var start = 0 to 0
var end = lines.size - 1 to 0
for (y in lines.indices) {
for (x in lines[y].indices) {
if (y == 0 && lines[y][x] == '.') {
start = 0 to x
}
if (y == lines.size - 1 && lines[y][x] == '.') {
end = lines.size - 1 to x
}
grid[y to x] = lines[y][x]
}
}
return Triple(grid, start, end)
}
data class Edge(val v1: Point, val v2: Point, val weight: Int = 1)
}
fun main() {
val day23 = Day23()
val input = readInputAsString("day23.txt")
println("23, part 1: ${day23.part1(input)}")
println("23, part 2: ${day23.part2(input)}")
}
| 0 |
Kotlin
| 0 | 0 |
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
| 3,754 |
advent-of-code-2023
|
MIT License
|
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day08.kt
|
MichalChomo
| 572,214,942 | false |
{"Kotlin": 56758}
|
package eu.michalchomo.adventofcode.year2022
import eu.michalchomo.adventofcode.toInt
fun main() {
fun part1(input: List<String>): Int = input.map { it.map { it.digitToInt() } }
.let { rows ->
rows.mapIndexed { rowIndex, cols ->
cols.mapIndexed cols@{ colIndex, height ->
if (rowIndex !in 1 until rows.size - 1 || colIndex !in 1 until cols.size - 1) return@cols 0
listOf(
(cols.slice(0 until colIndex).all { it < height }),
(cols.slice(colIndex + 1 until cols.size).all { it < height }),
((0 until rowIndex).all { rows[it][colIndex] < height }),
((rowIndex + 1 until rows.size).all { rows[it][colIndex] < height })
).any { it }.toInt()
}.sum()
}.sum()
}.plus(input.size * 4 - 4)
fun part2(input: List<String>): Int = input.map { it.map { it.digitToInt() } }
.let { rows ->
rows.mapIndexed { rowIndex, cols ->
cols.mapIndexed cols@{ colIndex, height ->
if (rowIndex !in 1 until rows.size - 1 || colIndex !in 1 until cols.size - 1) return@cols 0
listOf(
(colIndex - 1 downTo 0).filter { cols[it] >= height }
.maxOrNull()?.let { colIndex - it } ?: colIndex,
(colIndex + 1 until cols.size).filter { cols[it] >= height }
.minOrNull()?.let { it - colIndex } ?: (cols.size - 1 - colIndex),
(rowIndex - 1 downTo 0).filter { rows[it][colIndex] >= height }
.maxOrNull()?.let { rowIndex - it } ?: rowIndex,
(rowIndex + 1 until rows.size).filter { rows[it][colIndex] >= height }
.minOrNull()?.let { it - rowIndex } ?: (rows.size - 1 - rowIndex),
).reduce { a, b -> a * b }
}.max()
}.max()
}
val testInput = readInputLines("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInputLines("Day08")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
a95d478aee72034321fdf37930722c23b246dd6b
| 2,272 |
advent-of-code
|
Apache License 2.0
|
src/main/kotlin/day15/Day15.kt
|
cyril265
| 433,772,262 | false |
{"Kotlin": 39445, "Java": 4273}
|
package day15
import readToList
import java.util.*
private val input = readToList("day15.txt")
fun main() {
val weightMatrix = input.map { line ->
line.chars().map { char ->
Character.getNumericValue(char)
}.toArray()
}.toTypedArray()
val distance = dijkstra(weightMatrix)
println(distance[weightMatrix.size - 1][weightMatrix[0].size - 1])
}
fun dijkstra(graph: Array<IntArray>): Array<IntArray> {
val dist = Array(graph.size) { _ -> IntArray(graph[0].size) { Int.MAX_VALUE } }
dist[0][0] = 0
val vis = Array(graph.size) { _ -> BooleanArray(graph[0].size) }
val pq = PriorityQueue(Comparator.comparing(NodeDistance::dist))
pq.add(NodeDistance(Node(0, 0, 0), 0))
while (pq.isNotEmpty()) {
val (index, minValue) = pq.poll()
vis[index.i][index.j] = true
if (dist[index.i][index.j] < minValue) continue
for (edge in adjacent(graph, index.i, index.j)) {
if (vis[edge.i][edge.j]) continue;
val newDist = dist[index.i][index.j] + edge.cost
if (newDist < dist[edge.i][edge.j]) {
dist[edge.i][edge.j] = newDist
pq.add(NodeDistance(edge, newDist))
}
}
}
return dist
}
private data class NodeDistance(val node: Node, val dist: Int)
private data class Node(val i: Int, val j: Int, val cost: Int)
private fun adjacent(matrix: Array<IntArray>, rowIndex: Int, columnIndex: Int): List<Node> {
return listOfNotNull(
get(matrix, rowIndex + 1, columnIndex),
get(matrix, rowIndex - 1, columnIndex),
get(matrix, rowIndex, columnIndex + 1),
get(matrix, rowIndex, columnIndex - 1),
)
}
private fun get(matrix: Array<IntArray>, rowIndex: Int, columnIndex: Int): Node? {
if (rowIndex >= 0 && rowIndex < matrix.size) {
val row = matrix[rowIndex]
if (columnIndex >= 0 && columnIndex < row.size) {
return Node(rowIndex, columnIndex, row[columnIndex])
}
}
return null
}
| 0 |
Kotlin
| 0 | 0 |
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
| 2,039 |
aoc2021
|
Apache License 2.0
|
src/Day15.kt
|
astrofyz
| 572,802,282 | false |
{"Kotlin": 124466}
|
import java.awt.font.NumericShaper.Range
fun main() {
fun readCoordinates(input: String): List<List<Int>> {
val regex = "(-?\\d+)".toRegex()
return regex.findAll(input).map { it.groups[1]?.value?.toInt() ?: 0 }.toList().chunked(2)
}
fun IntRange.myIntersect(other: IntRange): Boolean{
return (this.start <= other.endInclusive)&&(other.start <= this.endInclusive)
}
fun IntRange.myAdjacent(other: IntRange): Boolean{
return (this.last + 1)==other.first
}
fun part1(input: List<String>, yRef: Int): Pair<Int, MutableList<IntRange>> {
val pairSensorBeacon = input.map { readCoordinates(it) }.toList()
val rangesNoBeacon = mutableListOf<IntRange>()
var beaconsInRef = mutableSetOf<List<Int>>()
pairSensorBeacon.forEach {
var d = kotlin.math.abs(it[0][0]-it[1][0]) + kotlin.math.abs(it[0][1] - it[1][1])
if (it[1][1] == yRef) beaconsInRef.add(it[1])
if (d >= kotlin.math.abs(yRef - it[0][1])){
rangesNoBeacon.add(it[0][0]-(d - kotlin.math.abs(yRef - it[0][1])) .. it[0][0]+(d - kotlin.math.abs(yRef - it[0][1])))
}
}
rangesNoBeacon.sortBy { it.first }
val nonIntersectingRanges = mutableListOf<IntRange>()
nonIntersectingRanges.add(rangesNoBeacon[0])
for (range in rangesNoBeacon){
if (nonIntersectingRanges.takeLast(1)[0].myIntersect(range)){
nonIntersectingRanges[nonIntersectingRanges.size-1] =
minOf(nonIntersectingRanges[nonIntersectingRanges.size-1].first, range.first) ..
maxOf(nonIntersectingRanges[nonIntersectingRanges.size-1].last, range.last)
}
else if (nonIntersectingRanges.takeLast(1)[0].myAdjacent(range)){
nonIntersectingRanges[nonIntersectingRanges.size-1] =
minOf(nonIntersectingRanges[nonIntersectingRanges.size-1].first, range.first) ..
maxOf(nonIntersectingRanges[nonIntersectingRanges.size-1].last, range.last)
}
else nonIntersectingRanges.add(range)
}
return Pair(nonIntersectingRanges.sumOf { it.count() } - beaconsInRef.size, nonIntersectingRanges)
}
fun part2(input: List<String>, searchRegion: Int): Int {
val pairSensorBeacon = input.map { readCoordinates(it) }.toList()
val pairSensorDist = pairSensorBeacon.map {
Pair(Pair(it[0][0], it[0][1]), kotlin.math.abs(it[0][0]-it[1][0]) + kotlin.math.abs(it[0][1] - it[1][1]))
}.toList()
pairSensorDist.sortedBy { it.first.first }
var intersections = mutableSetOf<Pair<Int, Int>>()
for (i in pairSensorDist.indices){
for (j in i until pairSensorDist.size){
if (pairSensorDist[j].first.first - pairSensorDist[i].first.first > pairSensorDist[j].second + pairSensorDist[i].second) {
break
}
var biList = listOf<Int>(pairSensorDist[i].first.second - pairSensorDist[i].first.first + pairSensorDist[i].second,
pairSensorDist[i].first.second - pairSensorDist[i].first.first - pairSensorDist[i].second)
var BiList = listOf<Int>(pairSensorDist[i].first.second + pairSensorDist[i].first.first + pairSensorDist[i].second,
pairSensorDist[i].first.second + pairSensorDist[i].first.first - pairSensorDist[i].second)
var bjList = listOf<Int>(pairSensorDist[j].first.second - pairSensorDist[j].first.first + pairSensorDist[j].second,
pairSensorDist[j].first.second - pairSensorDist[j].first.first - pairSensorDist[j].second)
var BjList = listOf<Int>(pairSensorDist[j].first.second + pairSensorDist[j].first.first + pairSensorDist[j].second,
pairSensorDist[j].first.second + pairSensorDist[j].first.first - pairSensorDist[j].second)
for (bi in biList){
for (Bj in BjList){
var interPoint = Pair((Bj - bi)/2, (Bj + bi)/2)
if ((interPoint.first in 0 .. searchRegion)&&(interPoint.second in 0 .. searchRegion)){
intersections.add(interPoint)}
}
}
for (Bi in BiList){
for (bj in bjList){
var interPoint = Pair((Bi - bj)/2, (Bi + bj)/2)
if ((interPoint.first in 0 .. searchRegion)&&(interPoint.second in 0 .. searchRegion)){
intersections.add(interPoint)}
}
}
}
}
fun Pair<Int, Int>.notInside(): Boolean {
for (sensor in pairSensorDist){
if (kotlin.math.abs(this.first - sensor.first.first)+ kotlin.math.abs(this.second-sensor.first.second) <= sensor.second) {
return false
}
}
return true
}
loop@ for (point in intersections){
for (step in listOf(Pair(0, 1), Pair(0, -1), Pair(1, 0), Pair(-1, 0))){
if (Pair(point.first+step.first, point.second+step.second).notInside()){
if ((point.first+step.first in 0 .. searchRegion)&&(point.second+step.second in 0 .. searchRegion)) {
var answer:Long = (point.first + step.first).toLong()*searchRegion.toLong()+point.second + step.second
println(answer)
break@loop
}
}
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
println(part1(testInput, 10).first)
part2(testInput, 20)
val input = readInput("Day15")
println(part1(input, 2000000).first)
part2(input, 4000000)
}
| 0 |
Kotlin
| 0 | 0 |
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
| 5,954 |
aoc22
|
Apache License 2.0
|
src/main/kotlin/Beacons.kt
|
alebedev
| 573,733,821 | false |
{"Kotlin": 82424}
|
import kotlin.math.abs
fun main() = Beacons.solve(0..4_000_000)
private object Beacons {
fun solve(possibleCoordinates: IntRange) {
val sensors = readInput()
val distress = findDistressBeacon(sensors, possibleCoordinates)
println("Distress breacon at $distress, freq: ${distress.x.toBigInteger() * 4_000_000.toBigInteger() + distress.y.toBigInteger()}")
}
private fun findDistressBeacon(sensors: List<Sensor>, possibleCoordinates: IntRange): Pos {
for (y in possibleCoordinates) {
val ranges: List<IntRange> = rangesAtRow(sensors, y)
var prev: IntRange? = null
for (range in ranges) {
if (prev == null) {
prev = range
continue
}
if (range.last <= prev.last) {
continue
} else if (range.first <= prev.last) {
prev = prev.first..range.last
} else {
if (prev.last in possibleCoordinates) {
return Pos(prev.last + 1, y)
}
}
}
}
throw Error("Distress beacon not found")
}
// Problem 1
private fun solveIntersections(sensors: List<Sensor>, targetRow: Int) {
val ranges: List<IntRange> = rangesAtRow(sensors, targetRow)
// Calculate intersections
var result = 0
var currentRange: IntRange? = null
for (range in ranges) {
if (currentRange == null) {
currentRange = range
} else {
if (range.last <= currentRange.last) continue
else if (range.first <= currentRange.last) {
currentRange = currentRange.first..range.last
} else {
result += currentRange.last - currentRange.start + 1
currentRange = range
}
}
}
if (currentRange != null) {
result += currentRange.last - currentRange.start + 1
}
println("Beacon cannot take $result positions in row $targetRow")
}
private fun readInput(): List<Sensor> = generateSequence(::readLine).map {
val groupValues =
"Sensor at x=([-\\d]+), y=([-\\d]+): closest beacon is at x=([-\\d]+), y=([-\\d]+)".toRegex()
.matchEntire(it)!!.groupValues
Sensor(
Pos(groupValues[1].toInt(10), groupValues[2].toInt(10)),
Pos(groupValues[3].toInt(10), groupValues[4].toInt(10))
)
}.toList()
private fun rangesAtRow(sensors: List<Sensor>, targetRow: Int): List<IntRange> =
sensors.filter { abs(targetRow - it.pos.y) <= it.distanceToBeacon() }.map {
val dx = it.distanceToBeacon() - abs(targetRow - it.pos.y)
(it.pos.x - dx)..(it.pos.x + dx)
}.sortedBy { it.start }
data class Pos(val x: Int, val y: Int) {
fun distanceTo(other: Pos): Int = abs(x - other.x) + abs(y - other.y)
}
data class Sensor(val pos: Pos, val nearestBeacon: Pos) {
fun distanceToBeacon(): Int = pos.distanceTo(nearestBeacon)
}
}
| 0 |
Kotlin
| 0 | 0 |
d6ba46bc414c6a55a1093f46a6f97510df399cd1
| 3,200 |
aoc2022
|
MIT License
|
15/part_two.kt
|
ivanilos
| 433,620,308 | false |
{"Kotlin": 97993}
|
import java.io.File
import java.util.PriorityQueue
fun readInput() : Grid {
val input = File("input.txt")
.readText()
.split("\r\n")
.filter { it.isNotEmpty() }
.map { row -> row.map { it.digitToInt() }}
return Grid(input)
}
class Grid(mat : List<List<Int>>) {
companion object {
val deltaX = listOf(1, 0, -1, 0)
val deltaY = listOf(0, 1, 0, -1)
const val INF = 1e9.toInt()
const val DIRECTIONS = 4
const val MAP_SCALE = 5
const val MAX_COST = 9
}
private val mat : List<List<Int>>
private val rows : Int
private val cols : Int
init {
this.mat = mat
rows = mat.size
cols = mat[0].size
}
fun minCostToEnd() : Int {
return dijkstra(0, 0, MAP_SCALE * rows - 1, MAP_SCALE * cols - 1)
}
private fun dijkstra(startX : Int, startY : Int, endX : Int, endY : Int) : Int {
val distance = Array(MAP_SCALE * rows) { IntArray(MAP_SCALE * cols) { INF }}
distance[0][0] = 0
val pq = PriorityQueue()
{ o1: Triple<Int, Int, Int>, o2: Triple<Int, Int, Int> ->
if (o1.first < o2.first) -1 else 1
}
pq.add(Triple(0, startX, startY))
while(pq.isNotEmpty()) {
val (cost, x, y) = pq.peek()
pq.remove()
if (cost > distance[x][y]) continue
for (dir in 0 until DIRECTIONS) {
val nx = x + deltaX[dir]
val ny = y + deltaY[dir]
if (isIn(nx, ny)) {
val moveCost = calcMoveCost(nx, ny)
if (distance[nx][ny] > distance[x][y] + moveCost) {
distance[nx][ny] = distance[x][y] + moveCost
pq.add(Triple(distance[nx][ny], nx, ny))
}
}
}
}
return distance[endX][endY]
}
private fun isIn(x : Int, y : Int) : Boolean {
return x in 0 until MAP_SCALE * rows && y in 0 until MAP_SCALE * cols
}
fun calcMoveCost(x : Int, y : Int) : Int {
val originalMapCost = mat[x % rows][y % cols]
val scaleAdd = (x / rows) + (y / cols)
val result = (originalMapCost + scaleAdd) % MAX_COST
return if (result == 0) MAX_COST else result
}
}
fun solve(grid : Grid) : Int {
return grid.minCostToEnd()
}
fun main() {
val grid = readInput()
val ans = solve(grid)
println(ans)
}
| 0 |
Kotlin
| 0 | 3 |
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
| 2,485 |
advent-of-code-2021
|
MIT License
|
src/day8/puzzle08.kt
|
brendencapps
| 572,821,792 | false |
{"Kotlin": 70597}
|
package day8
import Puzzle
import PuzzleInput
import java.io.File
import java.lang.Integer.max
data class TreeProperties(val height: Int, val row: Int, val col: Int, private val initialScore: Int) {
var top = initialScore
var bottom = initialScore
var left = initialScore
var right = initialScore
fun visible(): Boolean {
return height > left || height > right || height > bottom || height > top
}
fun visibleScore(): Int {
return top * left * right * bottom
}
}
class TreeIterator(val input: Day8PuzzleInput) {
fun iterate(op: (TreeProperties) -> Boolean): Int {
return iterate(0 until input.rows, 0 until input.cols, op)
}
fun iterate(rows: IntProgression, cols: IntProgression, op: (TreeProperties) -> Boolean): Int {
var index = 0
for(row in rows) {
for(col in cols) {
index++
if(!op(input.trees[row][col])) {
return index
}
}
}
return index
}
fun <T> map(op: (TreeProperties) -> T) : List<T> {
return map(0 until input.rows, 0 until input.cols, op)
}
fun <T> map(rows: IntProgression, cols: IntProgression, op: (TreeProperties) -> T) : List<T> {
val list = mutableListOf<T>()
for(row in rows) {
for(col in cols) {
list.add(op(input.trees[row][col]))
}
}
return list
}
fun <T> left(tree: TreeProperties, op: (TreeProperties) -> T): T {
return op(input.trees[tree.row][tree.col - 1])
}
fun <T> up(tree: TreeProperties, op: (TreeProperties) -> T): T {
return op(input.trees[tree.row - 1][tree.col])
}
fun <T> right(tree: TreeProperties, op: (TreeProperties) -> T): T {
return op(input.trees[tree.row][tree.col + 1])
}
fun <T> down(tree: TreeProperties, op: (TreeProperties) -> T): T {
return op(input.trees[tree.row + 1][tree.col])
}
}
fun day8Puzzle() {
Day8PuzzleSolution().solve(Day8PuzzleInput("inputs/day8/example.txt", -1, 21))
Day8PuzzleSolution().solve(Day8PuzzleInput("inputs/day8/input.txt", -1, 1851))
Day8Puzzle2Solution().solve(Day8PuzzleInput("inputs/day8/example.txt", 0, 8))
Day8Puzzle2Solution().solve(Day8PuzzleInput("inputs/day8/input.txt", 0, 574080))
}
class Day8PuzzleInput(val input: String, initialScore: Int, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) {
val trees: List<List<TreeProperties>>
val rows: Int
val cols: Int
val iterator: TreeIterator
init {
trees = File(input).readLines().mapIndexed { rowIndex, row ->
row.toCharArray().mapIndexed {colIndex, tree ->
TreeProperties(tree.digitToInt(), rowIndex, colIndex, initialScore)
}
}
rows = trees.size
cols = trees[0].size
iterator = TreeIterator(this)
}
}
class Day8PuzzleSolution : Puzzle<Int, Day8PuzzleInput>() {
override fun solution(input: Day8PuzzleInput): Int {
input.iterator.iterate(1 until input.rows, 1 until input.cols) { tree ->
tree.top = input.iterator.up(tree) { max(it.top, it.height) }
tree.left = input.iterator.left(tree) { max(it.left, it.height) }
true
}
input.iterator.iterate(input.rows - 2 downTo 0, input.cols - 2 downTo 0) { tree ->
tree.bottom = input.iterator.down(tree) { max(it.bottom, it.height) }
tree.right = input.iterator.right(tree) { max(it.right, it.height) }
true
}
return input.iterator.map(input.trees.indices, input.trees[0].indices) { it.visible() }.count { it }
}
}
class Day8Puzzle2Solution : Puzzle<Int, Day8PuzzleInput>() {
override fun solution(input: Day8PuzzleInput): Int {
input.iterator.iterate { tree ->
tree.top = input.iterator.iterate(tree.row - 1 downTo 0, tree.col .. tree.col) { otherTree ->
tree.height > otherTree.height
}
tree.left = input.iterator.iterate(tree.row .. tree.row, tree.col - 1 downTo 0) { otherTree ->
tree.height > otherTree.height
}
true
}
input.iterator.iterate(input.rows - 1 downTo 0, input.cols - 1 downTo 0) { tree ->
tree.bottom = input.iterator.iterate(tree.row + 1 until input.rows, tree.col .. tree.col) { otherTree ->
tree.height > otherTree.height
}
tree.right = input.iterator.iterate(tree.row .. tree.row, tree.col + 1 until input.cols) { otherTree ->
tree.height > otherTree.height
}
true
}
return input.iterator.map { tree -> tree }.maxOf { it.visibleScore() }
}
}
| 0 |
Kotlin
| 0 | 0 |
00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3
| 4,953 |
aoc_2022
|
Apache License 2.0
|
src/day20/d20_2.kt
|
svorcmar
| 720,683,913 | false |
{"Kotlin": 49110}
|
fun main() {
val input = ""
val k = input.toInt()
val ceil = Math.ceil(input.toDouble()).toInt() / 11
// sieve[i] == 0 iff i is prime
// == k iff k is a prime divisor of i
val sieve = sieve(ceil)
val memo = Array<Map<Int, Int>?>(sieve.size) { null }
for (i in 2 until sieve.size) {
val s = elfFunction(i, sieve, memo)
if (s >= k) {
println(i)
break
}
}
}
fun elfFunction(n: Int, sieve: Array<Int>, memo: Array<Map<Int, Int>?>): Int =
11 * allDivisors(primeDivisors(n, sieve, memo)).filter { n / it <= 50 }.sum()
fun primeDivisors(n: Int, sieve: Array<Int>, memo: Array<Map<Int, Int>?>): Map<Int, Int> {
val r = memo[n]
if (r != null)
return r
val c = if (sieve[n] == 0)
mapOf(n to 1)
else
primeDivisors(n / sieve[n], sieve, memo).toMutableMap().also { it.merge(sieve[n], 1, Int::plus) }
memo[n] = c
return c
}
fun allDivisors(primeDivs: Map<Int, Int>) = allDivisorsRec(primeDivs.entries.map { (k, v) -> k to v }.toList(), 0, 1)
fun allDivisorsRec(primeDivs: List<Pair<Int, Int>>, idx: Int, acc: Int): Sequence<Int> = sequence {
if (idx == primeDivs.size) {
yield(acc)
} else {
for (i in 0 .. primeDivs[idx].second) {
yieldAll(allDivisorsRec(primeDivs, idx + 1, acc * Math.pow(primeDivs[idx].first.toDouble(), i.toDouble()).toInt()))
}
}
}
fun sieve(n: Int): Array<Int> {
val arr = Array(n + 1) { 0 }
for (i in 2 .. n) {
if (arr[i] == 0) {
for (m in 2 * i .. n step i) {
arr[m] = i
}
}
}
return arr
}
| 0 |
Kotlin
| 0 | 0 |
cb097b59295b2ec76cc0845ee6674f1683c3c91f
| 1,542 |
aoc2015
|
MIT License
|
cz.wrent.advent/Day16.kt
|
Wrent
| 572,992,605 | false |
{"Kotlin": 206165}
|
package cz.wrent.advent
import java.lang.Integer.max
import java.util.Deque
import java.util.LinkedList
fun main() {
// println(partOne(test))
// val result = partOne(input)
// println("16a: $result")
println(partTwo(test))
println("16b: ${partTwo(input)}")
}
private fun partOne(input: String): Int {
val valves = input.toValves()
calculateDistances(valves)
return recursiveSolution(valves)
}
private fun recursiveSolution(valves: Map<String, Valve>): Int {
val meaningful = valves.values.filter { it.flowRate > 0 }.sortedByDescending { it.flowRate }.map { it.label }
return meaningful.map { process("AA", it, 30, 0, emptyList(), meaningful, valves) }.maxOf { it }
}
private fun process(
current: String,
next: String,
minutes: Int,
released: Int,
opened: List<String>,
meaningful: List<String>,
valves: Map<String, Valve>
): Int {
val distance = valves[current]!!.distances[next]!!
val time = minutes - distance - 1
if (time < 1) {
return released
}
val nextReleased = released + time * valves[next]!!.flowRate
val nextOpened = opened + next
if (meaningful.size == nextOpened.size) {
return nextReleased
} else {
return meaningful.filterNot { nextOpened.contains(it) }
.map { process(next, it, time, nextReleased, nextOpened, meaningful, valves) }.maxOf { it }
}
}
fun <T> List<T>.permutations(): List<List<T>> =
if (isEmpty()) listOf(emptyList()) else mutableListOf<List<T>>().also { result ->
for (i in this.indices) {
(this - this[i]).permutations().forEach {
result.add(it + this[i])
}
}
}
private fun calculateDistances(valves: Map<String, Valve>) {
valves.values.filter { it.label == "AA" || it.flowRate > 0 }.forEach { curr ->
curr.distances = calculateDistances(curr, valves)
}
}
private fun calculateDistances(from: Valve, valves: Map<String, Valve>): Map<String, Int> {
val nextValves: Deque<Pair<String, Int>> = LinkedList(listOf(from.label to 0))
val map = mutableMapOf<String, Int>()
while (nextValves.isNotEmpty()) {
val next = nextValves.pop()
map[next.first] = next.second
val nextValve = valves[next.first]!!
val nextDistance = next.second + 1
nextValve.leadsTo.forEach {
if (map[it] == null || map[it]!! > nextDistance)
nextValves.push(it to next.second + 1)
}
}
return map
}
private fun partTwo(input: String): Int {
val valves = input.toValves()
calculateDistances(valves)
return recursiveSolutionWithElephant(valves)
}
private fun recursiveSolutionWithElephant(valves: Map<String, Valve>): Int {
val meaningful = valves.values.filter { it.flowRate > 0 }.sortedByDescending { it.flowRate }.map { it.label }
return meaningful.map { i ->
meaningful.map { j ->
if (i == j) -1 else processWithElephant("AA", "AA", i, j, 26, 26, 0, emptyList(), meaningful, valves)
}.maxOf { it }
}.maxOf { it }
}
private fun processWithElephant(
current: String,
currentElephant: String,
next: String,
nextElephant: String,
minutes: Int,
elephantMinutes: Int,
released: Int,
opened: List<String>,
meaningful: List<String>,
valves: Map<String, Valve>
): Int {
val distance = valves[current]!!.distances[next]!!
val time = minutes - distance - 1
val elephantDistance = valves[currentElephant]!!.distances[nextElephant]!!
val elephantTime = elephantMinutes - elephantDistance - 1
if (time < 1 && elephantTime < 1) {
return released
}
var nextReleased = released
var nextOpened = opened
if (time > 0) {
nextReleased += time * valves[next]!!.flowRate
nextOpened = nextOpened + next
}
if (elephantTime > 0) {
nextReleased += elephantTime * valves[nextElephant]!!.flowRate
nextOpened = nextOpened + nextElephant
}
if (meaningful.size == nextOpened.size) {
if (nextReleased > best) {
best = nextReleased
println(best)
}
return nextReleased
} else {
val filtered = meaningful.filterNot { nextOpened.contains(it) }
if (!canBeBetterThanBest(nextReleased, max(time, elephantTime), filtered, valves)) {
return -1
}
return filtered.map { i ->
filtered.map { j ->
if (i == j) -1 else processWithElephant(
next,
nextElephant,
i,
j,
time,
elephantTime,
nextReleased,
nextOpened,
meaningful,
valves
)
}.maxOf { it }
}.maxOf { it }
}
}
private fun canBeBetterThanBest(
nextReleased: Int,
max: Int,
filtered: List<String>,
valves: Map<String, Valve>
): Boolean {
val b = nextReleased + filtered.mapIndexed { i, label ->
valves[label]!!.flowRate * (max - (2 * i))
}.sumOf { it }
// println("$best : $b")
return b > best
}
var best = 1488
private data class Next(
val label: String,
val time: Int,
val released: Int,
val alreadyReleased: MutableSet<String> = mutableSetOf()
)
private fun String.toValves(): Map<String, Valve> {
val regex = Regex("Valve (.+) has flow rate=(\\d+); tunnels? leads? to valves? (.*)")
return this.split("\n")
.map { regex.matchEntire(it)!!.groupValues }
.map { Valve(it.get(1), it.get(2).toInt(), it.get(3).split(", ")) }
.map { it.label to it }
.toMap()
}
private data class Valve(
val label: String,
val flowRate: Int,
val leadsTo: List<String>,
var opened: Boolean = false,
var distances: Map<String, Int> = emptyMap()
)
private const val test = """Valve AA has flow rate=0; tunnels lead to valves DD, II, BB
Valve BB has flow rate=13; tunnels lead to valves CC, AA
Valve CC has flow rate=2; tunnels lead to valves DD, BB
Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE
Valve EE has flow rate=3; tunnels lead to valves FF, DD
Valve FF has flow rate=0; tunnels lead to valves EE, GG
Valve GG has flow rate=0; tunnels lead to valves FF, HH
Valve HH has flow rate=22; tunnel leads to valve GG
Valve II has flow rate=0; tunnels lead to valves AA, JJ
Valve JJ has flow rate=21; tunnel leads to valve II"""
private const val input =
"""Valve QZ has flow rate=0; tunnels lead to valves IR, FA
Valve FV has flow rate=0; tunnels lead to valves AA, GZ
Valve GZ has flow rate=0; tunnels lead to valves FV, PO
Valve QL has flow rate=0; tunnels lead to valves MR, AA
Valve AA has flow rate=0; tunnels lead to valves QL, GQ, EV, FV
Valve SQ has flow rate=23; tunnel leads to valve ZG
Valve PK has flow rate=8; tunnels lead to valves MN, GN, WF, TY, CX
Valve GQ has flow rate=0; tunnels lead to valves AA, MT
Valve TI has flow rate=22; tunnels lead to valves GM, CS
Valve JU has flow rate=17; tunnels lead to valves TT, RR, UJ, JY
Valve YD has flow rate=7; tunnels lead to valves AT, ZS, BS
Valve YB has flow rate=0; tunnels lead to valves EA, MW
Valve FA has flow rate=0; tunnels lead to valves QZ, JT
Valve TN has flow rate=0; tunnels lead to valves ZS, PO
Valve MW has flow rate=0; tunnels lead to valves YB, YL
Valve XN has flow rate=0; tunnels lead to valves VL, VM
Valve MN has flow rate=0; tunnels lead to valves PK, TT
Valve IP has flow rate=9; tunnels lead to valves YC, SA, CH, PI
Valve PD has flow rate=0; tunnels lead to valves YZ, VM
Valve ZS has flow rate=0; tunnels lead to valves TN, YD
Valve PC has flow rate=0; tunnels lead to valves MR, XT
Valve VM has flow rate=13; tunnels lead to valves CX, XN, PD
Valve PO has flow rate=4; tunnels lead to valves GZ, TN, SA, XT, BM
Valve GN has flow rate=0; tunnels lead to valves PK, YL
Valve YL has flow rate=5; tunnels lead to valves MT, YZ, GN, SU, MW
Valve IR has flow rate=6; tunnels lead to valves LK, PI, BM, QZ, EV
Valve GM has flow rate=0; tunnels lead to valves TI, RH
Valve CS has flow rate=0; tunnels lead to valves UJ, TI
Valve EA has flow rate=18; tunnels lead to valves VL, YB, WF, JY
Valve LK has flow rate=0; tunnels lead to valves IR, MR
Valve BM has flow rate=0; tunnels lead to valves IR, PO
Valve JZ has flow rate=0; tunnels lead to valves RH, RR
Valve SA has flow rate=0; tunnels lead to valves IP, PO
Valve XT has flow rate=0; tunnels lead to valves PO, PC
Valve YC has flow rate=0; tunnels lead to valves IP, IL
Valve RH has flow rate=15; tunnels lead to valves WJ, JZ, GM
Valve CH has flow rate=0; tunnels lead to valves IP, BS
Valve JY has flow rate=0; tunnels lead to valves EA, JU
Valve TY has flow rate=0; tunnels lead to valves WJ, PK
Valve WJ has flow rate=0; tunnels lead to valves TY, RH
Valve IL has flow rate=0; tunnels lead to valves YC, MR
Valve BS has flow rate=0; tunnels lead to valves YD, CH
Valve AT has flow rate=0; tunnels lead to valves YD, UX
Valve UJ has flow rate=0; tunnels lead to valves CS, JU
Valve VL has flow rate=0; tunnels lead to valves EA, XN
Valve JT has flow rate=21; tunnels lead to valves ZG, FA
Valve UX has flow rate=10; tunnel leads to valve AT
Valve RR has flow rate=0; tunnels lead to valves JZ, JU
Valve TT has flow rate=0; tunnels lead to valves JU, MN
Valve MT has flow rate=0; tunnels lead to valves GQ, YL
Valve EV has flow rate=0; tunnels lead to valves AA, IR
Valve ZG has flow rate=0; tunnels lead to valves JT, SQ
Valve WF has flow rate=0; tunnels lead to valves EA, PK
Valve YZ has flow rate=0; tunnels lead to valves PD, YL
Valve MR has flow rate=3; tunnels lead to valves LK, IL, QL, SU, PC
Valve PI has flow rate=0; tunnels lead to valves IR, IP
Valve CX has flow rate=0; tunnels lead to valves VM, PK
Valve SU has flow rate=0; tunnels lead to valves YL, MR"""
| 0 |
Kotlin
| 0 | 0 |
8230fce9a907343f11a2c042ebe0bf204775be3f
| 9,177 |
advent-of-code-2022
|
MIT License
|
src/main/kotlin/Day08.kt
|
uipko
| 572,710,263 | false |
{"Kotlin": 25828}
|
fun main() {
val visibleTrees = visibleTrees("Day08.txt")
println("Visible trees $visibleTrees")
val score = scenicScore("Day08.txt")
println("Visible trees $score")
}
fun visibleTrees(fileName: String): Int {
val forrest = readInput(fileName).map { line -> line.toCharArray().map { it.digitToInt() }}
var visible = forrest.size*2 + forrest.first().size*2 - 4
forrest.drop(1).dropLast(1).forEachIndexed() {row, line ->
line.drop(1).dropLast(1).forEachIndexed() { col, tree ->
if (forrest[row+1].subList(0,col+1).max() < tree || // left
forrest[row+1].subList(minOf(col + 2, forrest[0].size), forrest[0].size).maxOf { it } < tree || // right
(0..row).maxOf { forrest[it][col + 1] } < tree || // top
(minOf( forrest.size-1, row+2) until forrest.size).maxOf { forrest[it][col+1] } < tree // bottom
) {
visible++
}
}
}
return visible
}
fun scenicScore(fileName: String): Int {
val forrest = readInput(fileName).map { line -> line.toCharArray().map { it.digitToInt() }}
var topScore = 0
forrest.forEachIndexed() { row, line ->
line.forEachIndexed() { col, tree ->
if (col > 0 && row > 0 && col < line.size-1 && row < forrest.size-1) {
val left = run { (col - 1 downTo 0).fold(0) { acc, it ->
val result = acc.inc()
if (line[it] >= tree) return@run result
result
} } // left
val top = run { (row - 1 downTo 0).fold(0) { acc, it ->
val result = acc.inc()
if (forrest[it][col] >= tree) return@run result
result
} }// top
val right = run { (col + 1 until line.size).fold(0) { acc, it ->
val result = acc.inc()
if (line[it] >= tree) return@run result
result
} } // right
val bottom = run { (row + 1 until forrest.size).fold(0) { acc, it ->
val result = acc.inc()
if (forrest[it][col] >= tree) return@run result
result
} } // bottom
val score = left * top * right * bottom
topScore = maxOf(score, topScore)
}
}
}
return topScore
}
| 0 |
Kotlin
| 0 | 0 |
b2604043f387914b7f043e43dbcde574b7173462
| 2,445 |
aoc2022
|
Apache License 2.0
|
src/Day05.kt
|
davedupplaw
| 573,042,501 | false |
{"Kotlin": 29190}
|
fun main() {
fun readCrateStack(input: List<String>, indexOfBlankLine: Int): MutableMap<Int, List<String>> {
val stack = input
.take(indexOfBlankLine)
.map {
it.chunked(4)
.mapIndexed { index, crate ->
index to crate.replace("[", "").replace("]", "").trim()
}
.filter { p -> p.second.isNotBlank() }
}
.dropLast(1)
.flatten()
.groupBy { it.first + 1 }
.mapValues { it.value.reversed().map { v -> v.second } }
.toMutableMap()
return stack
}
fun readMoves(input: List<String>, indexOfBlankLine: Int): List<Triple<Int, Int, Int>> {
val regex = """move (\d+) from (\d+) to (\d+)""".toRegex()
return input
.drop(indexOfBlankLine)
.filter { it.isNotBlank() }
.map {
val values = regex.find(it)!!.groupValues
Triple(values[1].toInt(), values[2].toInt(), values[3].toInt())
}
}
fun processMoves(stack: MutableMap<Int, List<String>>, moves: List<Triple<Int, Int, Int>>) {
moves.forEach { move ->
repeat(move.first) {
val topOfStack = stack[move.second]!!.last()
stack[move.third] = stack[move.third]!!.plus(topOfStack)
stack[move.second] = stack[move.second]!!.dropLast(1)
}
}
}
fun processMovesWith9001(stack: MutableMap<Int, List<String>>, moves: List<Triple<Int, Int, Int>>) {
moves.forEach { move ->
val topOfStack = stack[move.second]!!.takeLast(move.first)
stack[move.third] = stack[move.third]!!.plus(topOfStack)
stack[move.second] = stack[move.second]!!.dropLast(move.first)
}
}
fun getTopOfStacks(stack: MutableMap<Int, List<String>>): List<String> {
println("At end: $stack")
return stack.entries.sortedBy { it.key }.map { it.value.lastOrNull() ?: " " }
}
fun part1(input: List<String>): String {
val indexOfBlankLine = input.indexOfFirst { it.isBlank() }
val stack = readCrateStack(input, indexOfBlankLine)
val moves = readMoves(input, indexOfBlankLine)
processMoves(stack, moves)
return getTopOfStacks(stack).joinToString("") { it }
}
fun part2(input: List<String>): String {
val indexOfBlankLine = input.indexOfFirst { it.isBlank() }
val stack = readCrateStack(input, indexOfBlankLine)
val moves = readMoves(input, indexOfBlankLine)
processMovesWith9001(stack, moves)
return getTopOfStacks(stack).joinToString("") { it }
}
val test = readInput("Day05.test")
val part1test = part1(test)
println("part1 test: $part1test")
check(part1test == "CMZ")
val part2test = part2(test)
println("part2 test: $part2test")
check(part2test == "MCD")
val input = readInput("Day05")
val part1 = part1(input)
println("Part1: $part1")
val part2 = part2(input)
println("Part2: $part2")
}
| 0 |
Kotlin
| 0 | 0 |
3b3efb1fb45bd7311565bcb284614e2604b75794
| 3,225 |
advent-of-code-2022
|
Apache License 2.0
|
2k23/aoc2k23/src/main/kotlin/12.kt
|
papey
| 225,420,936 | false |
{"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117}
|
package d12
import input.read
fun main() {
println("Part 1: ${part1(read("12.txt"))}")
println("Part 2: ${part2(read("12.txt"))}")
}
fun part1(input: List<String>): Long = input.sumOf {
val (springs, sizes) = it.split(" ").let { parts ->
val springs = parts.first().toCharArray().toList()
// ensure group is closed
springs.addLast('.')
Pair(springs, parts[1].split(",").map { number -> number.toInt() })
}
solve(springs, sizes)
}
fun part2(input: List<String>): Long = input.sumOf {
val (springs, sizes) = it.split(" ").let { parts ->
val baseSprings = parts.first()
val springs = List(5) { baseSprings }.joinToString("?").toMutableList()
// ensure group is closed
springs.addLast('.')
val baseSizes = parts[1].split(",").map { number -> number.toInt() }
Pair(springs, List(5) { baseSizes }.flatten())
}
solve(springs, sizes)
}
class State(private val springs: List<Char>, private val sizes: List<Int>, private val doneInGroup: Int) {
override fun hashCode(): Int {
return 31 * springs.hashCode() + sizes.hashCode() + doneInGroup.hashCode()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as State
if (springs != other.springs) return false
if (sizes != other.sizes) return false
if (doneInGroup != other.doneInGroup) return false
return true
}
}
fun solve(springs: List<Char>, sizes: List<Int>): Long = solve(springs, sizes, 0, hashMapOf())
fun solve(springs: List<Char>, sizes: List<Int>, doneInGroup: Int, memo: MutableMap<State, Long>): Long {
if (springs.isEmpty()) {
if (sizes.isEmpty() && doneInGroup == 0) {
return 1
}
return 0
}
val state = State(springs, sizes, doneInGroup)
if (memo.containsKey(state)) {
return memo[state]!!
}
var solutions = 0L
val candidates = if (springs.first() == '?') listOf('#', '.') else listOf(springs.first())
candidates.forEach { c ->
when (c) {
'#' -> {
solutions += solve(springs.drop(1), sizes, doneInGroup + 1, memo)
}
'.' -> {
if (doneInGroup != 0) {
if (sizes.isNotEmpty() && sizes.first() == doneInGroup) {
solutions += solve(springs.drop(1), sizes.drop(1), 0, memo)
}
} else {
solutions += solve(springs.drop(1), sizes, 0, memo)
}
}
}
}
memo[state] = solutions
return solutions
}
| 0 |
Rust
| 0 | 3 |
cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5
| 2,730 |
aoc
|
The Unlicense
|
src/main/kotlin/y2016/day04/Day04.kt
|
TimWestmark
| 571,510,211 | false |
{"Kotlin": 97942, "Shell": 1067}
|
package y2016.day04
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
fun input(): Rooms {
return AoCGenerics.getInputLines("/y2016/day04/input.txt")
.map {
Room(
checkSum = it.split("[")[1].dropLast(1),
id = it.split("[")[0].split("-").last().toInt(),
name = it.split("[")[0].split("-").dropLast(1).joinToString("")
)
}
}
typealias Rooms = List<Room>
data class Room(
val name: String,
val id: Int,
val checkSum: String
)
fun Room.valid(): Boolean {
val charCountMap = sortedMapOf<Char, Int>()
this.name.forEach {
if (charCountMap.containsKey(it)) {
charCountMap[it] = charCountMap[it]?.plus(1)
} else {
charCountMap[it] = 1
}
}
val result = mutableListOf<Char>()
while (result.size < 5) {
val maxOccurrences = charCountMap.maxByOrNull { it.value }!!.value
val allWithMax = charCountMap.filter { it.value == maxOccurrences }.keys.sorted()
result.addAll(allWithMax)
allWithMax.forEach { charCountMap.remove(it) }
}
val calculatedCheck = result.take(5).joinToString("")
return calculatedCheck == this.checkSum
}
const val alphabet = "abcdefghijklmnopqrstuvwxyz"
fun Room.decrypt(): String = this.name.map { char ->
alphabet[(alphabet.indexOf(char) + this.id) % 26]
}.joinToString("")
fun part1(): Int {
return input().filter { it.valid() }.sumOf { it.id }
}
fun part2(): Int {
val room = input()
.filter { it.valid() }
.first { it.decrypt().contains("northpole") }
return room.id
}
| 0 |
Kotlin
| 0 | 0 |
23b3edf887e31bef5eed3f00c1826261b9a4bd30
| 1,716 |
AdventOfCode
|
MIT License
|
src/Day12.kt
|
oleksandrbalan
| 572,863,834 | false |
{"Kotlin": 27338}
|
import java.util.LinkedList
fun main() {
val input = readInput("Day12")
.filterNot { it.isEmpty() }
.map { it.toCharArray() }
val rows = input.size
val columns = input.first().size
var s = Vertex(0, 0)
var e = Vertex(0, 0)
repeat(rows) { i ->
repeat(columns) { j ->
if (input[i][j] == 'S') {
input[i][j] = 'a'
s = Vertex(i, j)
}
if (input[i][j] == 'E') {
input[i][j] = 'z'
e = Vertex(i, j)
}
}
}
val graph = Graph()
graph.init(input)
val distances = graph.vertices
.associateWith { Int.MAX_VALUE }
.toMutableMap()
distances[e] = 0
val queue = LinkedList<Vertex>()
queue.add(e)
while (queue.isNotEmpty()) {
val vertex = queue.pop()
graph.getNeighbours(vertex).forEach {
val oldDistance = distances[it] ?: 0
val newDistance = (distances[vertex] ?: 0) + 1
if (newDistance < oldDistance) {
distances[it] = newDistance
queue.add(it)
}
}
}
val part1 = distances[s]
println("Part1: $part1")
val part2 = distances
.filterKeys { input[it.row][it.column] == 'a' }
.minOf { it.value }
println("Part2: $part2")
}
private fun Graph.init(input: List<CharArray>) {
val rows = input.size
val columns = input.first().size
repeat(rows) { i ->
repeat(columns) { j ->
val vertex = Vertex(i, j)
buildList {
if (i > 0) add(Vertex(i - 1, j))
if (j > 0) add(Vertex(i, j - 1))
if (i < rows - 1) add(Vertex(i + 1, j))
if (j < columns - 1) add(Vertex(i, j + 1))
}.filter {
val from = input[i][j]
val to = input[it.row][it.column]
(from.code - to.code) <= 1
}.forEach {
add(vertex, it)
}
}
}
}
private data class Vertex(val row: Int, val column: Int)
private class Graph {
private val neighbours = mutableMapOf<Vertex, MutableList<Vertex>>()
val vertices: List<Vertex> get() = neighbours.keys.toList()
fun add(from: Vertex, to: Vertex) {
val list = neighbours.getOrPut(from) { mutableListOf() }
list.add(to)
}
fun getNeighbours(vertex: Vertex): List<Vertex> =
requireNotNull(neighbours[vertex])
}
| 0 |
Kotlin
| 0 | 2 |
1493b9752ea4e3db8164edc2dc899f73146eeb50
| 2,504 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day09.kt
|
dragere
| 440,914,403 | false |
{"Kotlin": 62581}
|
import kotlin.streams.toList
fun main() {
fun part1(input: List<List<Int>>): Int {
val lowPoints = mutableListOf<Int>()
for (i in input.indices) {
for (j in input[i].indices) {
val v = input[i][j]
if (j > 0 && input[i][j - 1] <= v) continue
if (j < input[i].size - 1 && input[i][j + 1] <= v) continue
if (i > 0 && input[i - 1][j] <= v) continue
if (i < input.size - 1 && input[i + 1][j] <= v) continue
lowPoints.add(v)
}
}
return lowPoints.sumOf { it + 1 }
}
fun getAdjecent(p: Pair<Int, Int>): List<Pair<Int, Int>> {
return listOf(
Pair(p.first, p.second - 1),
Pair(p.first, p.second + 1),
Pair(p.first - 1, p.second),
Pair(p.first + 1, p.second)
)
}
fun explore(
field: List<List<Int>>,
low: Pair<Int, Int>,
exploredPoints: MutableSet<Pair<Int, Int>>
): List<Pair<Int, Int>> {
var tmp = getAdjecent(low)
.filter { !exploredPoints.contains(it) }
.filter { it.first >= 0 && it.first < field.size }
.filter { it.second >= 0 && it.second < field[0].size }
.filter { field[it.first][it.second] != 9 }
exploredPoints.addAll(tmp)
tmp = tmp.flatMap { explore(field, it, exploredPoints) }
val out = mutableListOf(low)
out.addAll(tmp)
return out
}
fun part2(input: List<List<Int>>): Int {
val exploredPoints = mutableSetOf<Pair<Int, Int>>()
val out = mutableListOf<Int>()
for (i in input.indices) {
for (j in input[i].indices) {
val point = Pair(i, j)
if (exploredPoints.contains(point)) continue
val v = input[i][j]
if (j > 0 && input[i][j - 1] <= v) continue
if (j < input[i].size - 1 && input[i][j + 1] <= v) continue
if (i > 0 && input[i - 1][j] <= v) continue
if (i < input.size - 1 && input[i + 1][j] <= v) continue
exploredPoints.add(point)
val tmp = explore(input, point, exploredPoints)
out.add(tmp.size)
}
}
return out.sortedDescending().subList(0, 3).foldRight(1) { i, acc -> acc * i }
}
fun preprocessing(input: String): List<List<Int>> {
return input.trim().split("\n").map { it.trim().chars().map { c -> c.toChar().digitToInt() }.toList() }.toList()
}
val realInp = read_testInput("real9")
val testInp = read_testInput("test9")
// val testInp = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
// println("Test 1: ${part1(preprocessing(testInp))}")
// println("Real 1: ${part1(preprocessing(realInp))}")
// println("-----------")
println("Test 2: ${part2(preprocessing(testInp))}")
println("Real 2: ${part2(preprocessing(realInp))}")
}
| 0 |
Kotlin
| 0 | 0 |
3e33ab078f8f5413fa659ec6c169cd2f99d0b374
| 3,034 |
advent_of_code21_kotlin
|
Apache License 2.0
|
src/main/kotlin/com/anahoret/aoc2022/day15/main.kt
|
mikhalchenko-alexander
| 584,735,440 | false | null |
package com.anahoret.aoc2022.day15
import java.io.File
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class Point(val x: Int, val y: Int) {
fun manhattanDistanceTo(other: Point): Int {
return abs(x - other.x) + abs(y - other.y)
}
}
class Sensor(position: Point, val closestBeacon: Point) {
val beaconDistance = position.manhattanDistanceTo(closestBeacon)
val x = position.x
val y = position.y
companion object {
private val regex = "Sensor at x=(.+), y=(.+): closest beacon is at x=(.+), y=(.+)".toRegex()
fun parse(str: String): Sensor {
val (_, sx, sy, bx, by) = regex.find(str)!!.groupValues
return Sensor(Point(sx.toInt(), sy.toInt()), Point(bx.toInt(), by.toInt()))
}
}
}
fun parse(str: String): List<Sensor> {
return str.split("\n")
.map(Sensor::parse)
}
fun main() {
val input = File("src/main/kotlin/com/anahoret/aoc2022/day15/input.txt")
.readText()
.trim()
.let(::parse)
// Part 1
part1(input)
// Part 2
part2(input)
}
fun IntRange.overlap(other: IntRange): IntRange {
return if (first in other) first..min(last, other.last)
else if (last in other) max(first, other.first)..last
else IntRange.EMPTY
}
fun IntRange.contains(other: IntRange): Boolean {
return other.first in this && other.last in this
}
fun IntRange.size() = if (isEmpty()) 0 else abs(this.last - this.first) + 1
private fun part1(sensors: List<Sensor>) {
val searchRow = 2000000
sensors.mapNotNull { findExcluded(it, searchRow) }
.let(::merge)
.sumOf(IntRange::size)
.let(::println)
}
private fun part2(sensors: List<Sensor>) {
val searchRange = 0..4000000
val beaconRanges = sensors.map(Sensor::closestBeacon)
.groupBy(Point::y)
.mapValues { (_, v) -> v.map { it.x..it.x } }
searchRange.asSequence()
.mapNotNull { y ->
val res = sensors
.mapNotNull { sensor -> findExcluded(sensor, y) }
.let { excludedRanges -> beaconRanges[y]?.let { excludedRanges + it } ?: excludedRanges }
.let(::merge)
.takeIf { it.size > 1 }
?.let { y to it.first().last + 1 }
res
}.first()
.let { (y, x) -> x.toLong() * 4000000 + y }
.let(::println)
}
fun merge(ranges: List<IntRange>): List<IntRange> {
val newRanges = ranges
.sortedBy(IntRange::first)
.fold(mutableListOf<IntRange>()) { acc, range ->
if (acc.isEmpty()) acc.add(range)
else {
val last = acc.last()
if (range.contains(last)) acc[acc.lastIndex] = range
else if (!last.contains(range)) {
val overlap = range.overlap(last)
val notConnected = overlap.isEmpty() && range.first > last.last + 1
if (notConnected) acc.add(range)
else acc[acc.lastIndex] = last.first..range.last
}
}
acc
}
return newRanges
}
fun findExcluded(sensor: Sensor, row: Int): IntRange? {
if (abs(sensor.y - row) > sensor.beaconDistance) return null
val minX = sensor.x - sensor.beaconDistance + abs(sensor.y - row)
val halfWidth = abs(sensor.x - minX)
return ((sensor.x - halfWidth)..(sensor.x + halfWidth))
.let {
when (sensor.closestBeacon.x) {
it.first -> it.first.inc()..it.last
it.last -> it.first..it.last.dec()
else -> it
}
}
}
| 0 |
Kotlin
| 0 | 0 |
b8f30b055f8ca9360faf0baf854e4a3f31615081
| 3,644 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/days/y2023/day11/Day11.kt
|
jewell-lgtm
| 569,792,185 | false |
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
|
package days.y2023.day11
import days.y2023.day10.PuzzleGrid
import util.InputReader
typealias PuzzleLine = List<Char>
typealias PuzzleInput = List<PuzzleLine>
class Day11(val input: PuzzleInput) {
fun partOne(): Int {
val galaxies = input.toGalaxyMap(2)
val pairs = galaxies.pairwise()
println("There are ${pairs.size} pairs")
return pairs.sumOf { (a, b) -> galaxies.nonManhattanDistance(a, b) }
}
}
data class Position(val y: Int, val x: Int)
fun <E> List<E>.pairwise(): List<Pair<E, E>> {
// return every combination of 2 elements from the list
return this.flatMapIndexed { i, e1 ->
this.subList(i + 1, this.size).map { e2 -> Pair(e1, e2) }
}
}
data class GalaxyMap(val positions: Set<Position>, val spaceExpansionQuotient: Int = 1) {
operator fun get(i: Int): Position {
return positions.toList()[i]
}
fun pairwise(): List<Pair<Position, Position>> {
return positions.toList().pairwise()
}
fun nonManhattanDistance(start: Position, end: Position): Int {
var dist = 0
var curr = start
while (curr.x != end.x) {
val travelCost = if (xIsEmpty(curr.x) )spaceExpansionQuotient else 1
dist += travelCost
curr = curr.copy(x = curr.x.unitTo(end.x))
}
while (curr.y != end.y) {
val travelCost = if (yIsEmpty(curr.y) )spaceExpansionQuotient else 1
dist += travelCost
curr = curr.copy(y = curr.y.unitTo(end.y))
}
return dist
}
private fun isGalaxy(point: Position) = point in positions
fun allPointsBetween(a: Position, b: Position): List<Position> {
// first go left/right
val route = mutableListOf(a)
while (route.last() != b) {
route.last().x.unitTo(b.x)
?.also { nextX -> route.add(route.last().copy(x = nextX)) }
route.last().y.unitTo(b.y)
?.also { nextY -> route.add(route.last().copy(y = nextY)) }
}
return route
}
private fun yIsEmpty(that: Int): Boolean {
return positions.none { it.y == that }
}
private fun xIsEmpty(that: Int): Boolean {
return positions.none { it.x == that }
}
fun at(y: Int, x: Int): Position =
positions.firstOrNull() { it.y == y && it.x == x } ?: error("Nothing at $y, $x")
}
private fun Int.unitTo(x: Int) = when {
this < x -> this + 1
this > x -> this - 1
else -> 0
}
fun Collection<Position>.toGalaxyMap(quo: Int): GalaxyMap = GalaxyMap(this.toSet(), spaceExpansionQuotient = quo)
fun PuzzleGrid.toGalaxyMap(spaceExpansionQuotient: Int = 1): GalaxyMap =
this.flatMapIndexed { y: Int, row: List<Char> ->
row.mapIndexedNotNull { x, char ->
if (char == '#') Position(y, x) else null
}
}.toGalaxyMap(spaceExpansionQuotient)
fun main() {
val year = 2023
val day = 11
val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day).map { line -> line.toList() }
val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day).map { line -> line.toList() }
println("${exampleInput.toGalaxyMap(2).let { map -> map.nonManhattanDistance(map.at(5, 1), map.at(9, 4)) }}")
println("${exampleInput.toGalaxyMap(2).let { map -> map.nonManhattanDistance(map.at(0, 3), map.at(8, 7)) }}")
println("${exampleInput.toGalaxyMap(2).let { map -> map.nonManhattanDistance(map.at(2, 0), map.at(6, 9)) }}")
println("${exampleInput.toGalaxyMap(2).let { map -> map.nonManhattanDistance(map.at(9, 0), map.at(9, 4)) }}")
assertEq(9, exampleInput.toGalaxyMap(2).let { map -> map.nonManhattanDistance(map.at(5, 1), map.at(9, 4)) })
assertEq(15, exampleInput.toGalaxyMap(2).let { map -> map.nonManhattanDistance(map.at(0, 3), map.at(8, 7)) })
assertEq(17, exampleInput.toGalaxyMap(2).let { map -> map.nonManhattanDistance(map.at(2, 0), map.at(6, 9)) })
assertEq(5, exampleInput.toGalaxyMap(2).let { map -> map.nonManhattanDistance(map.at(9, 0), map.at(9, 4)) })
fun partOne(input: PuzzleInput) = Day11(input).partOne()
println("Example 1: ${partOne(exampleInput)}")
println("Puzzle 1: ${partOne(puzzleInput)}")
}
fun <E> assertEq(a: E, b: E) {
if (a != b) {
error("Expected $a, got $b")
}
}
| 0 |
Kotlin
| 0 | 0 |
b274e43441b4ddb163c509ed14944902c2b011ab
| 4,329 |
AdventOfCode
|
Creative Commons Zero v1.0 Universal
|
src/main/day13/day13.kt
|
rolf-rosenbaum
| 572,864,107 | false |
{"Kotlin": 80772}
|
package day13
import java.util.*
import readInput
import second
sealed interface Packet : Comparable<Packet> {
data class ListPacket(val packets: MutableList<Packet> = mutableListOf()) : Packet {
override fun compareTo(other: Packet): Int {
return when (other) {
is IntPacket -> this.compareTo(other.toListPacket())
is ListPacket -> packets.compareTo(other.packets)
}
}
private fun Iterable<Packet>.compareTo(other: Iterable<Packet>): Int {
val left = Stack<Packet>()
this.reversed().forEach { left.push(it) }
val right = Stack<Packet>()
other.reversed().forEach { right.push(it) }
while (left.isNotEmpty()) {
val l = left.pop()
val r = if (right.isNotEmpty()) right.pop() else return 1
val comp = l.compareTo(r)
if (comp != 0) return comp
}
// left is empty is right also empty?
return if (right.isEmpty()) 0 else -1
}
}
data class IntPacket(val value: Int) : Packet {
override fun compareTo(other: Packet): Int {
return when (other) {
is ListPacket -> toListPacket().compareTo(other)
is IntPacket -> value.compareTo(other.value)
}
}
}
fun toListPacket(): Packet = ListPacket(mutableListOf(this))
companion object {
fun parse(input: String): Packet =
toPacket(
input.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex())
.filter { it.isNotBlank() }
.filterNot { it == "," }
.iterator()
)
private fun toPacket(input: Iterator<String>): Packet {
val packets = mutableListOf<Packet>()
while (input.hasNext()) {
when (val symbol = input.next()) {
"]" -> return ListPacket(packets)
"[" -> packets.add(toPacket(input))
else -> packets.add(IntPacket(symbol.toInt()))
}
}
return ListPacket(packets)
}
}
}
fun main() {
val input = readInput("main/day13/Day13")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val list = input.filter(String::isNotBlank).map {
Packet.parse(it)
}.chunked(2)
return list.mapIndexed { index, signals ->
if (signals.first() < signals.second())
index + 1
else
0
}.sum()
}
fun part2(input: List<String>): Int {
val firstDivider = Packet.parse("[[2]]")
val secondDivider = Packet.parse("[[6]]")
val list = (input.filter(String::isNotBlank).map {
Packet.parse(it)
} + listOf(firstDivider, secondDivider)).sorted()
return (list.indexOf(firstDivider) + 1) * (list.indexOf(secondDivider) + 1)
}
| 0 |
Kotlin
| 0 | 2 |
59cd4265646e1a011d2a1b744c7b8b2afe482265
| 2,972 |
aoc-2022
|
Apache License 2.0
|
src/Day08.kt
|
lonskiTomasz
| 573,032,074 | false |
{"Kotlin": 22055}
|
fun main() {
fun part1(input: List<String>) {
val matrix: List<List<Int>> = input.map { it.map { it.digitToInt() } }
val lastIndex = matrix.size - 1
val visibleTrees = matrix.withIndex().sumOf { (rowIndex, row) ->
when (rowIndex) {
0, lastIndex -> row.size
else -> {
row.withIndex().sumOf { (index, value) ->
when (index) {
0, lastIndex -> 1.toInt()
else -> {
val left = row.take(index)
val right = row.takeLast(row.size - index - 1)
val column = matrix.map { it[index] }
val top = column.take(rowIndex)
val bottom = column.takeLast(matrix.size - rowIndex - 1)
if (left.all { it < value } || right.all { it < value } ||
top.all { it < value } || bottom.all { it < value }) {
1
} else 0
}
}
}
}
}
}
println(visibleTrees)
}
fun part2(input: List<String>) {
fun List<Int>.visibleTrees(value: Int, withReverse: Boolean): Int {
var trees = 0
val list = if (withReverse) reversed() else this
for (v in list) {
trees++
if (v >= value) break
}
return trees
}
var maxScore = 0
val matrix: List<List<Int>> = input.map { it.map { it.digitToInt() } }
val lastIndex = matrix.size - 1
matrix.forEachIndexed { rowIndex, row ->
if (rowIndex !in listOf(0, lastIndex)) { // skip edges
val score = row.withIndex().maxOf { (index, value) ->
when (index) {
0, lastIndex -> 0 // skip edges
else -> {
val visibleLeftTrees =
row.take(index).visibleTrees(value, withReverse = true)
val visibleRightTrees = row.takeLast(row.size - index - 1)
.visibleTrees(value, withReverse = false)
val column = matrix.map { it[index] }
val visibleTopTrees =
column.take(rowIndex).visibleTrees(value, withReverse = true)
val visibleBottomTrees = column.takeLast(matrix.size - rowIndex - 1)
.visibleTrees(value, withReverse = false)
visibleLeftTrees * visibleRightTrees * visibleTopTrees * visibleBottomTrees
}
}
}
maxScore = maxOf(score, maxScore)
}
}
println(maxScore)
}
val inputTest = readInput("day08/input_test")
val input = readInput("day08/input")
part1(inputTest)
part1(input)
part2(inputTest)
part2(input)
}
| 0 |
Kotlin
| 0 | 0 |
9e758788759515049df48fb4b0bced424fb87a30
| 3,239 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/twentythree/Day01.kt
|
mihainov
| 573,105,304 | false |
{"Kotlin": 42574}
|
package twentythree
import readInputTwentyThree
enum class Numbers(val string: String, val number: Int) {
ONE("one", 1),
TWO("two", 2),
THREE("three", 3),
FOUR("four", 4),
FIVE("five", 5),
SIX("six", 6),
SEVEN("seven", 7),
EIGHT("eight", 8),
NINE("nine", 9)
}
fun String.firstNumberInString(): Int? {
return Numbers.values()
.map {
Pair(this.indexOf(it.string), it)
}.sortedBy {
it.first
}.filter {
it.first != -1
}.firstOrNull()?.second?.number
}
fun String.lastNumberInString(): Int? {
return Numbers.values()
.map {
Pair(this.lastIndexOf(it.string), it)
}.sortedBy {
it.first
}.filter {
it.first != -1
}.lastOrNull()?.second?.number
}
fun part1(input: List<String>): Int {
var result = 0
input.forEach {
for (i in it) {
if (i.isDigit()) {
result += i.digitToInt() * 10
break
}
}
for (i in it.reversed()) {
if (i.isDigit()) {
result += i.digitToInt()
break
}
}
}
return result
}
fun findFirstOccurrence(str: String): Int? {
str.forEachIndexed { index, c ->
if (c.isDigit()) {
return when (val it = str.substring(0, index).firstNumberInString()) {
null -> c.digitToInt()
else -> it
}
}
}
return str.firstNumberInString()
}
fun findLastOccurrence(str: String): Int? {
for (i in (0..str.length - 1).reversed()) {
if (str[i].isDigit()) {
return when (val it = str.substring(i).lastNumberInString()) {
null -> str[i].digitToInt()
else -> it
}
}
}
return str.lastNumberInString()
}
fun part2(input: List<String>): Int {
var result = 0;
input.forEach { str ->
print("$str: ")
result += (findFirstOccurrence(str).also(::print) ?: 0) * 10
result += findLastOccurrence(str).also(::print) ?: 0
println()
}
return result
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInputTwentyThree("Day01_test")
// check(part1(testInput).also(::println) == 142)
check(part2(testInput).also(::println) == 281)
val input = readInputTwentyThree("Day01")
println("Part1: ${part1(input)}")
println("Part2: ${part2(input)}")
}
| 0 |
Kotlin
| 0 | 0 |
a9aae753cf97a8909656b6137918ed176a84765e
| 2,551 |
kotlin-aoc-1
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.