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/aoc2022/day12/Day12.kt | svilen-ivanov | 572,637,864 | false | {"Kotlin": 53827} | package aoc2022.day12
import com.google.common.base.Stopwatch
import org.jetbrains.kotlinx.multik.api.d2array
import org.jetbrains.kotlinx.multik.api.mk
import org.jetbrains.kotlinx.multik.ndarray.data.*
import org.jetbrains.kotlinx.multik.ndarray.data.set
import readInput
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
private fun isOnMap(map: NDArray<Int, D2>): Boolean {
return x >= 0 && y >= 0 && x < map.shape[0] && y < map.shape[1]
}
fun canMoveTo(nextPoint: Point, map: NDArray<Int, D2>): Boolean {
return nextPoint.isOnMap(map) && (map[nextPoint.x, nextPoint.y] - map[x, y] <= 1)
}
fun toIndex(map: NDArray<Int, D2>): Int {
return x * map.shape[1] + y
}
companion object {
fun fromIndex(i: Int, map: NDArray<Int, D2>): Point {
return Point(i / map.shape[1], i % map.shape[1])
}
}
}
val dirs = listOf(Point(0, 1), Point(0, -1), Point(1, 0), Point(-1, 0))
class PathFinder(
private val map: NDArray<Int, D2>,
private val starts: List<Point>,
private val end: Point
) {
private val graph: Graph = Graph(map.shape[0] * map.shape[1])
init {
for (y in 0 until map.shape[1]) {
for (x in 0 until map.shape[0]) {
val curr = Point(x, y)
for (dir in dirs) {
val next = curr + dir
if (curr.canMoveTo(next, map)) {
val fromIndex = curr.toIndex(map)
val toIndex = next.toIndex(map)
graph.edges.add(Edge(fromIndex, toIndex, 1))
}
}
}
}
}
fun shortestPath(): Int {
val sw = Stopwatch.createStarted()
val min = starts.parallelStream().map { start ->
// println("${index}/${starts.size}")
val from = start.toIndex(map)
val distances = BellmanFord.getShortestPaths(graph, from)
for (destIndex in distances.indices) {
val dest = Point.fromIndex(destIndex, map)
if (dest == end) {
// println("\t" + i + " " + "\t\t" + if (distances[i] == Int.MAX_VALUE) "-" else distances[i])
return@map distances[destIndex]
}
}
error("No path found")
}.toList().min()
println("Time: ${sw.stop()}")
// println("Min: ${min}")
return min
}
}
fun main() {
fun part1(input: List<String>) {
val width = input.first().length
val height = input.size
val map = mk.d2array(width, height) { 0 }
// var start: Point? = null
val starts = mutableListOf<Point>()
var end: Point? = null
// println(map)
for ((y, line) in input.withIndex()) {
for ((x, elevation) in line.withIndex()) {
when (elevation) {
'S', 'a' -> {
starts.add(Point(x, y))
map[x, y] = 0
}
'E' -> {
end = Point(x, y)
map[x, y] = ('z' - 'a')
}
else -> map[x, y] = (elevation - 'a')
}
}
}
require(starts.isNotEmpty())
requireNotNull(end)
val path = PathFinder(map, starts, end).shortestPath()
println(path)
// println("-------------")
// for (y in 0 until map.shape[1]) {
// for (x in 0 until map.shape[0]) {
// val p = Point(x, y)
// val f = path.indexOf(p)
// print("%02d (%2s) : ".format(map[x, y], if (f >= 0) f else "."))
// }
// println()
// }
// println("Shortest path is:\n${path.joinToString("\n")}")
// println("Size: ${path.size - 1}")
}
fun part2(input: List<String>) {
}
val testInput = readInput("day12/day12")
part1(testInput)
part2(testInput)
}
| 0 | Kotlin | 0 | 0 | 456bedb4d1082890d78490d3b730b2bb45913fe9 | 4,137 | aoc-2022 | Apache License 2.0 |
src/day21/Day21.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day21
import readInput
fun main() {
fun parse(input: List<String>): List<Monkey> {
val monkeys = input.map { line ->
val split = line.split(": ")
Monkey(
name = split.first(),
yell = when {
(split.last().toIntOrNull() != null) -> { _ ->
split.last().toLong()
}
else -> {
val action = split.last().split(" ")
when (action[1]) {
"*" -> { monkeys ->
monkeys.first { it.name == action[0] }
.yell(monkeys) * monkeys.first { it.name == action[2] }.yell(monkeys)
}
"+" -> { monkeys ->
monkeys.first { it.name == action[0] }
.yell(monkeys) + monkeys.first { it.name == action[2] }.yell(monkeys)
}
"-" -> { monkeys ->
monkeys.first { it.name == action[0] }
.yell(monkeys) - monkeys.first { it.name == action[2] }.yell(monkeys)
}
"/" -> { monkeys ->
monkeys.first { it.name == action[0] }
.yell(monkeys) / monkeys.first { it.name == action[2] }
.yell(monkeys)
}
else -> error("Wrong input")
}
}
}
)
}
return monkeys
}
fun part1(input: List<String>): Long {
val monkeys = parse(input)
val rootMonkey = monkeys.find { monkey -> monkey.name == "root" }
return rootMonkey?.yell?.let { it(monkeys) } ?: 0
}
fun alterInput(input: List<String>): List<String> {
val alteredInput = input.toMutableList()
alteredInput.removeIf { it.contains("humn:") }
val rootLine = alteredInput.first { it.contains("root:") }
alteredInput.remove(rootLine)
val newRootLine = rootLine.replace("+", "-")
alteredInput.add(newRootLine)
return alteredInput
}
fun part2(input: List<String>): Long {
val alterInput = alterInput(input)
val monkeys = parse(alterInput)
val rootMonkey = monkeys.find { monkey -> monkey.name == "root" }
var i = 0L
var delta = 1_000_000_000_000L
while (true) {
val me = Monkey("humn") { _ -> i }
val root = rootMonkey?.yell?.let { it(monkeys + listOf(me)) } ?: 0
println("$i:$root")
if (root == 0L) {
return i
}
if (root < 0) {
i -= delta
delta /= 10
}
i += delta
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day21/Day21_test")
val input = readInput("day21/Day21")
check((part1(testInput)).also { println(it) } == 152L)
check((part1(input)).also { println(it) } == 38731621732448L)
// check(part2(testInput).also { println(it) } == 301L) TODO
println(part2(input))
}
data class Monkey(
val name: String,
val yell: (List<Monkey>) -> Long
)
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 3,492 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/_2022/Day02.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readInput
// seen more elegant solutions via myFigure - "X" - maps into number
// and you win when your figure = opponent's figure +1 (mod 3 ofc)
fun main() {
val scoreOfFigureMap = mapOf("X" to 1, "Y" to 2, "Z" to 3)
val enemyWinMap = mapOf("A" to "Z", "B" to "X", "C" to "Y")
val drawMap = mapOf("A" to "X", "B" to "Y", "C" to "Z")
fun scoreOfMyShape(figure: String): Int {
return scoreOfFigureMap.getOrDefault(figure, 0)
}
fun gameScore(enemyFigure: String, myFigure: String): Int {
if (drawMap.getOrDefault(enemyFigure, "") == myFigure) {
return 3
}
if (enemyWinMap.getOrDefault(enemyFigure, "") != myFigure) {
return 6
}
return 0
}
fun chooseFigure(enemyFigure: String, gameResult: String): String {
if ("X" == gameResult) {
// lose
return enemyWinMap.getOrDefault(enemyFigure, "")
} else if ("Y" == gameResult) {
// draw
return drawMap.getOrDefault(enemyFigure, "")
} else if ("Z" == gameResult) {
// win
var figure = "XYZ"
// not draw
figure = figure.replace(drawMap.getOrDefault(enemyFigure, ""), "")
// not lose
figure = figure.replace(enemyWinMap.getOrDefault(enemyFigure, ""), "")
return figure
}
return ""
}
fun part1(input: List<String>): Int {
return input.sumOf {
val split = it.split(' ')
var enemy = split[0]
var me = split[1]
var score = 0
score += scoreOfMyShape(me)
score += gameScore(enemy, me)
score
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val split = it.split(' ')
var enemyFigure = split[0]
var gameResult = split[1]
var myFigure = chooseFigure(enemyFigure, gameResult)
var score = 0
score += scoreOfMyShape(myFigure)
score += gameScore(enemyFigure, myFigure)
score
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 2,431 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day09/Day09.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day09
import readInput
import kotlin.math.abs
import kotlin.math.sign
data class Position(val x: Int, val y: Int) {
operator fun plus(direction: Direction): Position {
return Position(x + direction.x, y + direction.y)
}
fun inTouch(other: Position): Boolean {
return abs(x - other.x) <= 1 && abs(y - other.y) <= 1
}
}
enum class Direction(val char: Char, val x: Int, val y: Int) {
RIGHT('R', 1, 0),
LEFT('L', -1, 0),
UP('U', 0, 1),
DOWN('D', 0, -1);
companion object {
fun getByChar(c: Char): Direction {
return values().first { it.char == c }
}
}
}
data class State(val knots: List<Position>) {
fun move(direction: Direction): State {
val newRope = mutableListOf(knots.first() + direction)
for (i in 1 until knots.size) {
val knot = knots[i]
val head = newRope.last()
val tail = if (head.inTouch(knot)) {
knot
} else {
Position(knot.x + (head.x - knot.x).sign, knot.y + (head.y - knot.y).sign)
}
newRope.add(tail)
}
return State(newRope)
}
}
fun main() {
fun simulate(input: List<String>, n: Int): Int {
var state1 = State((0 until n).map { Position(0, 0) })
val visited = mutableSetOf<Position>()
input.forEach {
val direction = Direction.getByChar(it[0])
val count = it.substring(2).toInt()
repeat(count) {
state1 = state1.move(direction)
visited.add(state1.knots.last())
println("${direction.name} $state1")
}
}
return visited.size
}
fun part1(input: List<String>): Int {
return simulate(input, 2)
}
fun part2(input: List<String>): Int {
return simulate(input, 10)
}
val testInput = readInput("day09", "test")
val input = readInput("day09", "input")
check(part1(testInput) == 13)
println(part1(input))
val testInput2 = readInput("day09", "test2")
println(part2(testInput2))
check(part2(testInput2) == 36)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 2,193 | aoc2022 | Apache License 2.0 |
src/aoc2018/kot/Day13.kt | Tandrial | 47,354,790 | false | null | package aoc2018.kot
import java.io.File
import java.util.*
object Day13 {
data class Cart(var x: Int, var y: Int, var dX: Int = 0, var dY: Int = 0, var next: Int = 0, var alive: Boolean = true) : Comparable<Cart> {
override fun compareTo(other: Cart) = if (y == other.y) x.compareTo(other.x) else y.compareTo(other.y)
fun tick(tracks: List<String>) {
x += dX
y += dY
when (tracks[y][x]) {
'\\' -> dX = dY.also { dY = dX }
'/' -> dX = -dY.also { dY = -dX }
'+' -> {
when (next) { //rotation via complex numbers : left-turn = i, right-turn = -i
0 -> dX = dY.also { dY = -dX }
2 -> dX = -dY.also { dY = dX }
}
next = (next + 1) % 3
}
}
}
}
fun partOne(input: List<String>): String {
val carts = PriorityQueue<Cart>(getCarts(input))
while (true) {
carts.forEach { c ->
c.tick(input)
if (carts.any { c != it && c.x == it.x && c.y == it.y }) {
return "${c.x},${c.y}"
}
}
}
}
fun partTwo(input: List<String>): String {
val carts = getCarts(input).sorted().toMutableList()
while (carts.count { it.alive } > 1) {
carts.forEach { c ->
if (c.alive) {
c.tick(input)
carts.filter { it.alive && c != it && c.x == it.x && c.y == it.y }.forEach { it.alive = false; c.alive = false }
}
}
carts.sort()
}
val cart = carts.first { it.alive }
return "${cart.x},${cart.y}"
}
private fun getCarts(input: List<String>) = input.withIndex().flatMap { (y, line) ->
line.withIndex().mapNotNull { (x, value) ->
when (value) {
'^' -> Cart(x, y, dY = -1)
'v' -> Cart(x, y, dY = 1)
'<' -> Cart(x, y, dX = -1)
'>' -> Cart(x, y, dX = 1)
else -> null
}
}
}
}
fun main(args: Array<String>) {
val input = File("./input/2018/Day13_input.txt").readLines()
println("Part One = ${Day13.partOne(input)}")
println("Part Two = ${Day13.partTwo(input)}")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 2,054 | Advent_of_Code | MIT License |
src/year2022/day05/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2022.day05
import java.util.function.Function
import readInput
fun main() {
fun part1(input: List<String>, myFunc: Function<List<Char>, List<Char>> = Function { t: List<Char> -> t.reversed() }): String {
val origin: MutableMap<Int, MutableList<Char>> = input.subList(0, input.indexOf("")).map { it.chunked(4).map { it[1] } }
.reversed()
.drop(1)
.fold<List<Char>, MutableMap<Int, MutableList<Char>>>(mutableMapOf()) { acc, elem ->
acc.also {
elem.forEachIndexed { index, item -> acc.computeIfAbsent(index + 1) { mutableListOf() }.add(item) }
}
}.onEach { (_, l) -> l.removeIf { !it.isLetter() } }
val moves =
input.subList(input.indexOf("") + 1, input.size)
.map {
Regex("\\d+").findAll(it)
.map { it.value.toInt() }.toList()
}
.fold(origin) { acc, move ->
acc[move[2]]?.addAll(myFunc.apply(acc[move[1]]?.takeLast(move[0]) ?: emptyList()))
acc[move[1]] = acc[move[1]]?.dropLast(move[0])?.toMutableList() ?: mutableListOf()
acc
}.entries.sortedBy { it.key }.map { it.value.last() }.joinToString("")
return moves
}
fun part2(input: List<String>): String {
return part1(input, Function.identity())
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("year2022/day05/test")
println(part1(testInput))
check(part1(testInput) == "CMZ") { "expected \"CMZ\" but was ${part1(testInput)}" }
val input = readInput("year2022/day05/input")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 1,836 | adventOfCode | Apache License 2.0 |
2021/src/Day14.kt | Bajena | 433,856,664 | false | {"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454} | import java.util.*
// https://adventofcode.com/2021/day/14
fun main() {
fun step(string: String, rules: Map<String, Char>) : String {
var result = ""
string.zipWithNext().forEach {
result += it.first
result += rules.getOrDefault("${it.first}${it.second}", "")
}
result += string.last()
return result
}
var cache = mutableMapOf<Pair<String, Int>, Map<Char, Long>>()
fun compute(pair: String, rules: Map<String, Char>, maxLevel : Int = 10, current: Map<Char, Long> = mutableMapOf(), level: Int = 0) : Map<Char, Long> {
var newMap = current.toMutableMap()
if (cache.getOrDefault(Pair(pair, level), null) != null) {
cache[Pair(pair, level)]!!.forEach { (letter, count) -> newMap[letter] = newMap.getOrDefault(letter, 0) + count }
return newMap
}
val product = rules.getOrDefault(pair, null)
if (level == maxLevel || product == null) {
newMap[pair.first()] = newMap.getOrDefault(pair.first(), 0) + 1
newMap[pair.last()] = newMap.getOrDefault(pair.last(), 0) + 1
// cache[Pair(pair, level)] = newMap
return newMap
}
var resultLeft = compute("${pair.first()}$product", rules, maxLevel, newMap, level + 1).toMutableMap()
cache[Pair("${pair.first()}$product", level + 1)] = resultLeft
var resultRight = compute("$product${pair.last()}", rules, maxLevel, newMap, level + 1).toMutableMap()
cache[Pair("$product${pair.last()}", level + 1)] = resultRight
resultLeft.forEach { (letter, count) -> newMap[letter] = newMap.getOrDefault(letter, 0) + count }
resultRight.forEach { (letter, count) -> newMap[letter] = newMap.getOrDefault(letter, 0) + count }
newMap[product] = newMap.getOrDefault(product, 0) - 1
return newMap
}
fun part1() {
val rules = mutableMapOf<String, Char>()
var initial = ""
for (line in readInput("Day14")) {
if (line.isEmpty()) continue
if (initial.isEmpty()) {
initial = line
continue
}
val rule = line.split(" -> ")
rules[rule.first()] = rule.last().first()
}
var result = initial
println(initial)
for (i in 1..2) {
result = step(result, rules)
}
val occurences = result.groupingBy { it }.eachCount()
println(occurences)
println(occurences.values.maxOrNull()!! - occurences.values.minOrNull()!!)
}
fun part2() {
val rules = mutableMapOf<String, Char>()
var initial = ""
for (line in readInput("Day14")) {
if (line.isEmpty()) continue
if (initial.isEmpty()) {
initial = line
continue
}
val rule = line.split(" -> ")
rules[rule.first()] = rule.last().first()
}
var result = mutableMapOf<Char, Long>()
initial.zipWithNext().forEach {
var counts = compute("${it.first}${it.second}", rules, 40)
counts.forEach { (letter, count) -> result[letter] = result.getOrDefault(letter, 0) + count }
result[it.second] = result.getOrDefault(it.second, 0) - 1
}
result[initial.last()] = result.getOrDefault(initial.last(), 0) + 1
println(result.values.maxOrNull()!! - result.values.minOrNull()!!)
}
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a | 3,178 | advent-of-code | Apache License 2.0 |
src/Day14.kt | sitamshrijal | 574,036,004 | false | {"Kotlin": 34366} | fun main() {
fun parse(input: List<String>): List<CavePosition> {
val rocks = input.flatMap {
val splits = it.split(" -> ")
val list = mutableListOf<CavePosition>()
splits.zipWithNext().forEach { (start, end) ->
val x1 = start.substringBefore(",").toInt()
val y1 = start.substringAfter(",").toInt()
val x2 = end.substringBefore(",").toInt()
val y2 = end.substringAfter(",").toInt()
val xRange = minOf(x1, x2)..maxOf(x1, x2)
val yRange = minOf(y1, y2)..maxOf(y1, y2)
xRange.forEach { x ->
yRange.forEach { y ->
list += CavePosition(x, y)
}
}
}
list
}
return rocks.distinct()
}
fun part1(input: List<String>): Int {
val rocks = parse(input).toMutableList()
// Starting position
var sand = CavePosition(500, 0)
val maxY = rocks.maxOf { it.y }
var count = 0
while (sand.y <= maxY) {
// The first position the sand can move to; null otherwise
val next =
listOf(sand.down(), sand.downLeft(), sand.downRight()).firstOrNull { it !in rocks }
if (next != null) {
sand = next
} else {
rocks += sand
count++
// New unit of sand
sand = CavePosition(500, 0)
}
}
return count
}
fun part2(input: List<String>): Int {
return input.size
}
val input = readInput("input14")
println(part1(input))
println(part2(input))
}
data class CavePosition(val x: Int, val y: Int) {
fun down(): CavePosition = CavePosition(x, y + 1)
fun downLeft(): CavePosition = CavePosition(x - 1, y + 1)
fun downRight(): CavePosition = CavePosition(x + 1, y + 1)
}
| 0 | Kotlin | 0 | 0 | fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d | 1,987 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} | fun main() {
data class Range(val a: Int, val b: Int)
fun String.build(): Range {
val ab = this.split('-').map { it.toInt() }
return Range(ab[0], ab[1])
}
fun part1(input: List<String>): Int {
val result = input
.map { line -> line.split(',') }
.count { split ->
val (left, right) = split.map { it.build() }
(left.a <= right.a && right.b <= left.b) || (right.a <= left.a && left.b <= right.b)
}
return result
}
fun part2(input: List<String>): Int {
val result = input
.map { line -> line.split(',') }
.count { split ->
val (left, right) = split.map { it.build() }
(left.a <= right.a && right.a <= left.b) || (left.a <= right.b && right.b <= left.b) ||
(right.a <= left.a && left.a <= right.b) || (right.a <= left.b && left.b <= right.b)
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 576)
check(part2(testInput) == 905)
}
| 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 1,184 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day02/Day02.kt | mahmoud-abdallah863 | 572,935,594 | false | {"Kotlin": 16377} | package day02
import assertEquals
import readInput
import readTestInput
enum class RoundResult(val score: Int) {
Win(6),
Lost(0),
Draw(3);
companion object {
fun getFromString(s: Char): RoundResult = when(s) {
'X' -> Lost
'Y' -> Draw
else -> Win
}
}
}
enum class OptionShape(
private val index: Int,
val selectScore: Int
) {
Rock(0, 1),
Paper(1, 2),
Scissors(2, 3);
companion object {
fun getFromString(s: Char): OptionShape = when(s) {
'A', 'X' -> Rock
'B', 'Y' -> Paper
else -> Scissors
}
}
fun battle(other: OptionShape): RoundResult =
if (this.index == other.index) RoundResult.Draw
else if (other.index == (this.index + 1).mod(values().size)) RoundResult.Lost
else RoundResult.Win
fun findMoveForSecondPlayer(roundResult: RoundResult): OptionShape = when (roundResult) {
RoundResult.Draw -> this
RoundResult.Lost -> {
val index = (this.index - 1).mod(values().size)
values()[index]
}
else -> {
val index = (this.index + 1) % values().size
values()[index]
}
}
}
fun main() {
fun part1(input: List<String>): Int = input
.sumOf { line ->
val lineAsCharArray = line.toCharArray()
val p1Shape = OptionShape.getFromString(lineAsCharArray[0])
val p2Shape = OptionShape.getFromString(lineAsCharArray[2])
p2Shape.selectScore + p2Shape.battle(p1Shape).score
}
fun part2(input: List<String>): Int {
var score = 0
input.forEach { line ->
val lineAsCharArray = line.toCharArray()
val p1Shape = OptionShape.getFromString(lineAsCharArray[0])
val roundResult = RoundResult.getFromString(lineAsCharArray[2])
score += roundResult.score + p1Shape.findMoveForSecondPlayer(roundResult).selectScore
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput()
assertEquals(part1(testInput), 15)
assertEquals(part2(testInput), 12)
val input = readInput()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f6d1a1583267e9813e2846f0ab826a60d2d1b1c9 | 2,311 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/co/csadev/advent2021/Day16.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2021 by <NAME>
* Advent of Code 2021, Day 16
* Problem Description: http://adventofcode.com/2021/day/16
*/
package co.csadev.advent2021
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Resources.resourceAsText
class Day16(override val input: String = resourceAsText("21day16.txt")) :
BaseDay<String, Int, Long> {
private val transmission = input.map { it.digitToInt(16).toString(2).padStart(4, '0') }.joinToString("")
private val parsedTransmission = parse(transmission)
override fun solvePart1() = parsedTransmission.sumOfVersions()
override fun solvePart2() = parsedTransmission.value()
private fun parse(packet: String): Packet {
val type = packet.drop(3).take(3).toInt(2)
val rest = packet.drop(6)
return when (type) {
4 -> {
rest.chunked(5)
.let { it.takeWhile { g -> g.first() == '1' } + it.first { g -> g.first() == '0' } }
.let { Literal("${packet.take(6)}${it.joinToString("")}") }
}
else -> {
when (rest.first()) {
'0' -> {
val totalLength = rest.drop(1).take(15).toInt(2)
val subPackets = buildList<Packet> {
while (totalLength - sumOf { it.bits.length } > 0) {
parse(rest.drop(16 + sumOf { it.bits.length })).also { add(it) }
}
}
Operator("${packet.take(22)}${subPackets.joinToString("") { it.bits }}", subPackets)
}
else -> {
val subPacketsNumber = rest.drop(1).take(11).toInt(2)
val subPackets = buildList<Packet> {
repeat(subPacketsNumber) {
parse(rest.drop(12 + sumOf { it.bits.length })).also { add(it) }
}
}
Operator("${packet.take(18)}${subPackets.joinToString("") { it.bits }}", subPackets)
}
}
}
}
}
}
sealed class Packet(val bits: String) {
abstract fun sumOfVersions(): Int
abstract fun value(): Long
val type = bits.drop(3).take(3).toInt(2)
}
class Literal(bits: String) : Packet(bits) {
override fun sumOfVersions() = bits.take(3).toInt(2)
override fun value() = bits.drop(6)
.chunked(5)
.joinToString("") { it.drop(1) }
.toLong(2)
}
class Operator(bits: String, private val subs: List<Packet>) : Packet(bits) {
override fun sumOfVersions() = bits.take(3).toInt(2) + subs.sumOf { it.sumOfVersions() }
override fun value(): Long = when (type) {
0 -> subs.sumOf { it.value() }
1 -> subs.fold(1) { acc, packet -> acc * packet.value() }
2 -> subs.minOf { it.value() }
3 -> subs.maxOf { it.value() }
5 -> (subs[0].value() > subs[1].value()).toLong()
6 -> (subs[0].value() < subs[1].value()).toLong()
7 -> (subs[0].value() == subs[1].value()).toLong()
else -> error("Unsupported type $type")
}
private fun Boolean.toLong() = if (this) 1L else 0L
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 3,301 | advent-of-kotlin | Apache License 2.0 |
src/Day09.kt | ostersc | 572,991,552 | false | {"Kotlin": 46059} | import kotlin.math.absoluteValue
enum class Direction { U, D, L, R }
fun main() {
data class Point(var x: Int, var y: Int)
fun moveHead(rope: List<Point>, d: Direction, distance: Int, visitedLocations: MutableSet<Point>) {
repeat(distance) {
var head = rope[0]
when (d) {
Direction.U -> head.y += 1
Direction.D -> head.y -= 1
Direction.L -> head.x -= 1
Direction.R -> head.x += 1
}
print("Head is now at $head\t")
rope.indices.windowed(2, 1) { (hInd, tInd) ->
head = rope[hInd]
val tail = rope[tInd]
val origin = tail.copy()
if (((head.x - origin.x).absoluteValue <= 1 && (head.y - origin.y).absoluteValue <= 1)) {
print("They are touching, so not moving tail, so ")
} else {
if (head.x - origin.x > 1 || (head.x - origin.x == 1 && head.y != origin.y)) tail.x += 1 else if (origin.x - head.x > 1 || (origin.x - head.x == 1 && head.y != origin.y)) tail.x -= 1
if (head.y - origin.y > 1 || (head.y - origin.y == 1 && head.x != origin.x)) tail.y += 1 else if (origin.y - head.y > 1 || (origin.y - head.y == 1 && head.x != origin.x)) tail.y -= 1
}
}
visitedLocations.add(rope.last().copy())
println("Tail is now at ${rope.last()}")
}
}
fun moveRope(input: List<String>, rope: List<Point>): Int {
val visitedLocations = mutableSetOf(Point(0, 0))
for (line in input) moveHead(
rope, Direction.valueOf(line[0].toString()), line.substringAfter(' ').toInt(), visitedLocations
)
return visitedLocations.size
}
fun part1(input: List<String>): Int {
return moveRope(input, listOf(Point(0, 0), Point(0, 0)))
}
fun part2(input: List<String>): Int {
return moveRope(input, generateSequence { Point(0, 0) }.take(10).toList())
}
val part1Test = part1(readInput("Day09_test"))
println(part1Test)
check(part1Test == 13)
val part2Test = part2(readInput("Day09_test2"))
check(part2Test == 36)
val input = readInput("Day09")
println("\n\n==========")
val part1 = part1(input)
println(part1)
check(part1 == 6314)
val part2 = part2(input)
println(part2)
check(part2 == 2504)
}
| 0 | Kotlin | 0 | 1 | 3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9 | 2,449 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc2023/Day06.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import utils.InputUtils
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
fun main() {
val testInput = """Time: 7 15 30
Distance: 9 40 200""".trimIndent().split("\n")
fun distances(racetime: Int): Sequence<Int> = (1 until racetime)
.asSequence()
.map { it * (racetime - it) }
// Solve a*x^2 + b*x + c = 0
fun solveQuadratic(a:Double, b: Double,c: Double): Pair<Double, Double> {
val discriminant = b * b - 4 * a * c
// Assume there are 2 roots so we don't have to worry about complex numbers
val root1 = (-b + sqrt(discriminant)) / (2 * a)
val root2 = (-b - sqrt(discriminant)) / (2 * a)
return Pair(root1, root2)
}
fun distancesOver(raceTime: Long, target: Long): Long {
// x (t-x) = y
// xt-x^2-y = 0
val roots = solveQuadratic(-1.0, raceTime.toDouble(), (-target).toDouble())
val lower = ceil(roots.first).toLong()
val upper = floor(roots.second).toLong()
return 1 + (upper - lower)
}
fun part1(input: List<String>): Int {
val (times, distances) = input.map { it.substringAfter(":").listOfNumbers() }
val races = times.zip(distances)
return races.map { (time, distance) -> distances(time).count { it > distance } }.product()
}
fun part2(input: List<String>): Long {
val (time, distance) = input.map {
it.substringAfter(":").replace(" ", "").toLong() }
return distancesOver(time, distance)
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 288)
println(part2(testInput))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 6)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 1,904 | aoc-2022-kotlin | Apache License 2.0 |
2021/src/main/kotlin/day4_fast.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.IntGrid
import utils.Parser
import utils.Solution
fun main() {
Day4Fast.run()
}
object Day4All {
@JvmStatic fun main(args: Array<String>) {
mapOf("func" to Day4Func, "imp" to Day4Imp, "fast" to Day4Fast).forEach { (header, solution) ->
solution.run(header = header, skipPart1 = true, skipTest = true, printParseTime = false)
}
}
}
object Day4Fast : Solution<Pair<List<Int>, List<IntGrid>>>() {
override val name = "day4"
override val parser = Parser.compoundList(Parser.ints, IntGrid.table)
override fun part1(input: Pair<List<Int>, List<IntGrid>>): Int {
val (numbers, boards) = input
return solve(numbers, boards).first
}
override fun part2(input: Pair<List<Int>, List<IntGrid>>): Int {
val (numbers, boards) = input
return solve(numbers, boards).second
}
// given a list of numbers and a list of boards returns the score of the first winner and the last winner
private fun solve(numbers: List<Int>, boards: List<IntGrid>): Pair<Int, Int> {
// build a lookup table of number -> position
val numberPos = IntArray(numbers.maxOrNull()!! + 1)
numbers.forEachIndexed { index, number -> numberPos[number] = index }
// round index to board, we'll use this to get values
var first = Integer.MAX_VALUE to IntGrid.EMPTY
var last = Integer.MIN_VALUE to IntGrid.EMPTY
for (board in boards) {
var winningRound = Integer.MAX_VALUE
for (x in 0 until 5) {
var rowMax = Integer.MIN_VALUE
var colMax = Integer.MIN_VALUE
for (y in 0 until 5) {
// x=row y=col
val rowNum = numberPos[board[x][y]]
if (rowNum > rowMax) rowMax = rowNum
// abuse the same loop to check cols, x=col y=row
val colNum = numberPos[board[y][x]]
if (colNum > colMax) colMax = colNum
}
if (rowMax < winningRound) winningRound = rowMax
if (colMax < winningRound) winningRound = colMax
}
if (winningRound < first.first) first = winningRound to board
if (winningRound > last.first) last = winningRound to board
}
fun score(state: Pair<Int, IntGrid>): Int {
val (round, board) = state
var sum = 0
for (num in board.values) {
if (numberPos[num] > round) {
sum += num
}
}
return sum * numbers[round]
}
return score(first) to score(last)
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,404 | aoc_kotlin | MIT License |
src/Day03.kt | b0n541 | 571,797,079 | false | {"Kotlin": 17810} | fun main() {
fun stringsToCharSets(strings: List<String>) = strings.map { it.toSet() }
fun intersectAll(charSets: List<Set<Char>>) = charSets.reduce { first, second -> first intersect second }.single()
fun priority(char: Char) = when (char) {
in 'a'..'z' -> char - 'a' + 1
in 'A'..'Z' -> char - 'A' + 27
else -> error("Unsupported character $char")
}
fun part1(input: List<String>): Int {
return input.map {
stringsToCharSets(
listOf(
it.substring(0, it.length / 2),
it.substring(it.length / 2)
)
)
}
.map { intersectAll(it) }
.sumOf { priority(it) }
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map { stringsToCharSets(it) }
.map { intersectAll(it) }
.sumOf { priority(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
val input = readInput("Day03")
val resultTest1 = part1(testInput)
println("Test 1: $resultTest1")
check(resultTest1 == 157)
val resultPart1 = part1(input)
println("Part 1: $resultPart1")
check(resultPart1 == 7831)
val resultTest2 = part2(testInput)
println("Test 2: $resultTest2")
check(resultTest2 == 70)
val resultPart2 = part2(input)
println("Part 2: $resultPart2")
check(resultPart2 == 2683)
}
| 0 | Kotlin | 0 | 0 | d451f1aee157fd4d47958dab8a0928a45beb10cf | 1,511 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2021/Day08.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2021
import com.nibado.projects.advent.*
object Day08 : Day {
val values = resourceLines(2021, 8).map {
it.split("\\s*\\|\\s*".toRegex())
.let { (pattern, digits) -> pattern.split(' ') to digits.split(' ').map { it.trim() } }
}
override fun part1() = values.flatMap { it.second }.count { it.length in UNIQUE_LENGTHS }
override fun part2() = values.sumOf { (pattern, display) -> mapDisplay(display, createMapping(pattern)) }
private fun createMapping(pattern: List<String>): Map<Char, Int> {
val patternSets = pattern.map { it.toCharArray().toSet() }
val n1 = patternSets.single { it.size == 2 }
val n7 = patternSets.single { it.size == 3 }
val n4 = patternSets.single { it.size == 4 }
val n8 = patternSets.single { it.size == 7 }
var wire = CharArray(7)
wire[0] = (n7 - n1).single() //OK
val n3 = patternSets.single { it.size == 5 && it.containsAll(n1) } //OK
wire[6] = (n3 - n4 - wire[0]).single()
wire[4] = (n8 - n4 - n7 - wire[6]).single()
val n2 = patternSets.single { it.size == 5 && it != n3 && it.contains(wire[4]) }
val n5 = patternSets.single { it.size == 5 && it != n3 && it != n2 }
wire[1] = (n8 - n3 - n2).single()
wire[2] = (n1 - n5).single()
wire[5] = (n1 - wire[2]).single()
wire[3] = (n4 - setOf(wire[1], wire[2], wire[5])).single()
return wire.mapIndexed { index, c -> c to index }.toMap()
}
private fun mapDisplay(display: List<String>, mapping: Map<Char, Int>): Int {
val toSegments = display.map { d ->
d.map { c ->
mapping[c]!!
}.toSet()
}
val toInts = toSegments.map { segment -> DIGITS.indexOfFirst { it == segment } }
return toInts.joinToString("").toInt()
}
private val DIGITS = listOf(
setOf(0, 1, 2, 4, 5, 6),
setOf(2, 5),
setOf(0, 2, 3, 4, 6),
setOf(0, 2, 3, 5, 6),
setOf(1, 2, 3, 5),
setOf(0, 1, 3, 5, 6),
setOf(0, 1, 3, 4, 5, 6),
setOf(0, 2, 5),
setOf(0, 1, 2, 3, 4, 5, 6),
setOf(0, 1, 2, 3, 5, 6)
)
private val UNIQUE = listOf(1, 4, 7, 8)
private val UNIQUE_LENGTHS = UNIQUE.map { DIGITS[it].size }
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 2,382 | adventofcode | MIT License |
2022/src/main/kotlin/com/github/akowal/aoc/Day12.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
import kotlin.math.min
class Day12 {
private val map: Map<Point, Int>
private val start: Point
private val end: Point
init {
val lines = inputFile("day12").readLines()
start = lines.findPoint('S')
end = lines.findPoint('E')
map = lines.flatMapIndexed { y, row ->
row.mapIndexed { x, c ->
val height = when (c) {
'S' -> 'a'.code
'E' -> 'z'.code
else -> c.code
}
Point(x, y) to height
}
}.toMap()
}
fun solvePart1(): Int {
val dist = travel(end)
return dist.getValue(start)
}
fun solvePart2(): Int {
val dist = travel(end)
return map.filter { it.value == 'a'.code }.minOf { (p, _) -> dist[p] ?: Int.MAX_VALUE }
}
private fun travel(from: Point): Map<Point, Int> {
val visited = mutableSetOf<Point>()
val dist = mutableMapOf<Point, Int>()
var q = listOf(from)
var d = 0
dist[from] = 0
while (q.isNotEmpty()) {
val nextQ = mutableListOf<Point>()
for (p in q) {
if (!visited.add(p)) {
continue
}
dist[p] = min(d, dist[p] ?: Int.MAX_VALUE)
p.neighbors().filter { it in map }.forEach { n ->
if (map.getValue(p) - map.getValue(n) <= 1) {
nextQ += n
}
}
}
d++
q = nextQ
}
return dist
}
private fun List<String>.findPoint(c: Char) = indexOfFirst { c in it }.let { row -> Point(this[row].indexOf(c), row) }
private fun Point.neighbors() = listOf(
Point(x - 1, y),
Point(x + 1, y),
Point(x, y - 1),
Point(x, y + 1),
)
}
fun main() {
val solution = Day12()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 2,044 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/Day08.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | fun main() {
fun log(message: Any?) {
// println(message)
}
fun circumference(n: Int) = 4 * (n - 1)
fun iterPairsInside(n: Int) = sequence {
(1 until n - 1).forEach { x ->
(1 until n - 1).forEach { y ->
yield(Pair(x, y))
}
}
}
fun parse(input: List<String>): List<List<Int>> {
// val n: Int = input.first().length
// val grid: MutableList<MutableList<Int>> = MutableList(n) { mutableListOf(n) }
// input.forEachIndexed { i, line ->
// grid[i] = line.split("").drop(1).dropLast(1).map { it.toInt() }.toMutableList()
// }
// return grid
// TIL... digitToInt()
return input.map { row -> row.map { it.digitToInt() } }
}
fun part1(input: List<String>): Int {
val n: Int = input.first().length
val grid = parse(input)
var countVisible = 0
log("GRID of $n x $n\n$grid")
(1 until n - 1).forEach { y ->
(1 until n - 1).forEach { x ->
val target = grid[y][x]
val row = grid[y]
val visibleFromLeft = row.take(x).all { it < target }
val visibleFromRight = row.takeLast(n - x -1).all { it < target }
val column = grid.map { it[x] }
val visibleFromTop = column.take(y).all { it < target }
val visibleFromBottom = column.takeLast(n - y -1).all { it < target }
val visible = (visibleFromLeft || visibleFromRight || visibleFromTop || visibleFromBottom)
if (visible) { countVisible++ }
// log("($x, $y) [${target}] -> $visible [$visibleFromLeft, $visibleFromRight, $visibleFromTop, $visibleFromBottom]")
}
}
return circumference(n) + countVisible
}
fun scoreView(trees: List<Int>, target: Int): Int {
return minOf(trees.takeWhile { it < target }.size + 1, trees.size)
}
fun part2(input: List<String>): Int {
val n: Int = input.first().length
val grid = parse(input)
var bestScore = 0
// log("GRID of $n x $n\n$grid")
(0 until n).forEach { y ->
(0 until n).forEach { x ->
val target = grid[y][x]
val row = grid[y]
val visibleToLeft = scoreView(row.take(x).reversed(), target)
val visibleToRight = scoreView(row.takeLast(n - x - 1), target)
val column = grid.map { it[x] }
val visibleToTop = scoreView(column.take(y).reversed(), target)
val visibleToBottom = scoreView(column.takeLast(n - y - 1), target)
val score = (visibleToLeft * visibleToRight * visibleToTop * visibleToBottom)
bestScore = maxOf(bestScore, score)
log("($x, $y) [$target] [${score}] -> [$visibleToLeft, $visibleToRight, $visibleToTop, $visibleToBottom]")
}
}
return bestScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test.txt")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08.txt")
val p1 = part1(input)
println(">>> $p1")
check(p1 == 1703)
val p2 = part2(input)
println(">>> $p2")
check(p2 == 496650)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 3,381 | aoc2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day02.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
part1()
part2()
}
private fun part1() {
val maxR = 12
val maxG = 13
val maxB = 14
readInput(2023, 2).useLines { lines ->
val result = lines.map { line ->
val (id, gameInfo) = line.split(": ")
val gameNumber = id.split(" ").last().toInt()
val max = gameInfo.split("; ").map { game ->
game.split(", ").associate { pick ->
val (count, color) = pick.split(" ")
color to count.toInt()
}
}.fold(hashMapOf<String, Int>()) { acc, game ->
acc.apply {
for ((color, count) in game) {
if (getOrDefault(color, 0) < count) put(color, count)
}
}
}
gameNumber to max
}.fold(0) { acc, game ->
val (gameNumber, max) = game
val r = max.getOrDefault("red", 0)
val g = max.getOrDefault("green", 0)
val b = max.getOrDefault("blue", 0)
acc + when {
r <= maxR && g <= maxG && b <= maxB -> gameNumber
else -> 0
}
}
println(result)
}
}
private fun part2() {
readInput(2023, 2).useLines { lines ->
val result = lines.map { line ->
val (_, gameInfo) = line.split(": ")
val max = gameInfo.split("; ").map { game ->
game.split(", ").associate { pick ->
val (count, color) = pick.split(" ")
color to count.toInt()
}
}.fold(hashMapOf<String, Int>()) { acc, game ->
acc.apply {
for ((color, count) in game) {
if (getOrDefault(color, 0) < count) put(color, count)
}
}
}
max.values.fold(1) { acc, n -> acc * n }
}.fold(0) { acc, score -> acc + score }
println(result)
}
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 2,114 | adventofcode | Apache License 2.0 |
src/Day03.kt | mdtausifahmad | 573,116,146 | false | {"Kotlin": 5783} | import java.io.File
fun main(){
val groupSize = 3
val sumOfPriorities = File("src/Day03.txt")
.readText()
.also { println(it) }
.split("\n")
.flatMap { it.lines() }
.map { getCommonCharacters(it) }
.flatMap { it.map { elf -> getPriority(elf) } }
.sum()
println(sumOfPriorities)
val sunOfPriorities = File("src/Day03.txt")
.readText()
.split("\n")
.chunked(3)
.map { getBadgesFromRuckSacks(it) }
.sumOf { getPriority(it) }
println(sunOfPriorities)
}
fun getPriority(char: Char): Int {
return when {
char.isLowerCase() -> char - 'a' + 1
char.isUpperCase() -> char - 'A' + 27
else -> error("Check Input")
}
}
fun getCommonCharacters(input: String): Set<Char> {
val (firstCompartment,secondCompartment) = input.chunked(input.length / 2)
return firstCompartment.toSet() intersect secondCompartment.toSet()
}
fun getBadgesFromRuckSacks(ruckSacks: List<String>): Char{
val (first, second, third) = ruckSacks
return(first.toSet() intersect second.toSet() intersect third.toSet()).single()
}
fun solution1(){
File("src/Day03.txt")
.readText()
.split("\n")
.flatMap { it.lines() }
.map { it.chunked(it.length /2) }
.map { it[0].toSet() intersect it[1].toSet() }
.sumOf { getPriority(it.first()) }
}
| 0 | Kotlin | 0 | 0 | 13295fd5f5391028822243bb6880a98c70475ee2 | 1,421 | adventofcode2022 | Apache License 2.0 |
src/day13/Day13.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day13
import readInputAsString
private const val DAY_ID = "13"
private sealed class PacketItem: Comparable<PacketItem> {
data class Num(val x: Int) : PacketItem() {
fun toSeq(): Seq = Seq(listOf(this))
}
data class Seq(val items: List<PacketItem>) : PacketItem()
override fun compareTo(other: PacketItem): Int {
// base case #1
if (this is Num && other is Num) {
return compareValues(this.x, other.x)
}
// base case #2
if (this is Seq && other is Seq) {
var i = 0
while (i < minOf(this.items.size, other.items.size)) {
val res = this.items[i].compareTo(other.items[i])
if (res != 0) {
return res
}
i++
}
return when {
// check #1 - lists are of the same length and no comparison makes a decision about the order
this.items.size == other.items.size -> 0
// check #2 - the left list runs out of items first, the inputs are in the right order
i == this.items.size -> -1
// check #3 - the right list runs out of items first, the inputs are not in the right order
else -> 1
}
}
// if exactly one value is an integer, convert it to a list, then retry the comparison
if (this is Num) {
return this.toSeq().compareTo(other)
}
if (other is Num) {
return this.compareTo(other.toSeq())
}
return 0
}
companion object {
fun fromString(s: String): PacketItem {
var idx = 1
fun traverse(items: MutableList<PacketItem>): List<PacketItem> {
if (idx >= s.length) {
return items
}
val c = s[idx]
idx++
if (c == ']') {
return items
}
// parse Seq or Num
when {
c == '[' -> items += Seq(traverse(mutableListOf()))
c.isDigit() -> {
var x = c.digitToInt()
while (s[idx].isDigit()) {
x *= 10
x += s[idx].digitToInt()
idx++
}
items += Num(x)
}
}
// proceed to the next index, also ignoring commas
return traverse(items)
}
return Seq(traverse(mutableListOf()))
}
}
}
fun main() {
fun parseInput(input: String): List<Pair<PacketItem, PacketItem>> =
input.split("\n\n").map { pair ->
val res = pair.split("\n").map { PacketItem.fromString(it) }
res[0] to res[1]
}
fun part1(input: String): Int {
val pairs = parseInput(input)
val sum = pairs.foldIndexed(0) { index, acc, (left, right) ->
// sum indices (1-indexed) of the pairs that are in the right order
acc + if (compareValues(left, right) < 0) index + 1 else 0
}
return sum
}
fun part2(input: String): Int {
val dividers = sequenceOf("[[2]]", "[[6]]")
.map { PacketItem.fromString(it) }
.toSortedSet()
val pairs = parseInput(input)
val packets = dividers.toMutableList()
packets += pairs.flatMap { it.toList() }
// put the packets in the correct order
packets.sort()
// find the decoder key
val key = packets.foldIndexed(1) { index, acc, item ->
acc * if (item in dividers) index + 1 else 1
}
return key
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsString("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInputAsString("day${DAY_ID}/Day$DAY_ID")
println(part1(input)) // answer = 5013
println(part2(input)) // answer = 25038
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 4,184 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/advent2019/day14/day14.kt | davidpricedev | 225,621,794 | false | null | package advent2019.day14
import advent2019.util.pow
import kotlin.math.ceil
/**
* Part 2 Notes:
* naive option of starting fuel gueses at 1T/ore-for-1-fuel and incrementing up from there is waaaay to slow
* I could look for a way to turn my logic inside out maybe?
* Maybe there is an LCM/GCF solution in there somewhere? The more I think about it the more I'm certain there is
* and that that is probably the way I'm supposed to solve it.
* The other option would be to narrow in on the answer by varying the increments too - instead of +1, start with +10^n
* and decrement n as we overshoot
*/
fun main() {
// part1
println(calculateOreNeeded(getInputReactions()))
// part2
println(optimizeForOre(getInputReactions()))
}
data class ChemState(
val reactions: Map<String, Reaction>,
val needs: Map<String, Long>,
val has: Map<String, Long> = mapOf()
) {
// Done when only ore is needed
fun isDone() = needs.count() == 1 && needs.keys.first() == "ORE"
}
fun calculateOreNeeded(reactions: Map<String, Reaction>, fuelNeeded: Long = 1L, debug: Boolean = false): Long {
val init = ChemState(reactions, needs = mapOf("FUEL" to fuelNeeded))
return generateSequence(init) { state ->
if (debug) println(state)
calculateNext(state).takeIf { !state.isDone() }
}.last().needs.values.first()
}
/**
* Narrow in on the right answer by making big jumps and slowly scaling back the size of the jumps we are making
*/
fun optimizeForOre(reactions: Map<String, Reaction>, debug: Boolean = true): Long {
val oreProvided = 1000000000000
val oreFor1Fuel = calculateOreNeeded(reactions)
val startingFuelGuess = oreProvided / oreFor1Fuel
var guess = startingFuelGuess
for (n in 8 downTo 0) {
for (i in guess..Long.MAX_VALUE step 10L.pow(n)) {
val result = calculateOreNeeded(reactions, i)
if (debug) println("$i fuel requires $result ore")
if (result < oreProvided) {
// make sure guess is always the highest fuel value that hasn't exceeded ore provided
guess = i
} else if (n == 0) {
// incrementing is down to 1 so we've found the highest fuel inside the ore limits
return guess
} else {
// we've gone as far as we can with increment of 10^n, time to decrease n
break
}
}
}
return -1
}
fun calculateNext(state: ChemState): ChemState {
if (state.isDone()) return state
val entry = state.needs.entries.first { it.key != "ORE" }
val reaction = state.reactions[entry.key]
val amountNeeded = entry.value - (state.has[entry.key] ?: 0)
val reactionCount = reaction!!.reactionsNeededToProduce(amountNeeded)
val newNeeds = reaction.newNeeds(reactionCount)
val nextNeeds = combineMaps(state.needs.filterKeys { it != entry.key }, newNeeds)
val hasAmt = reactionCount * reaction.output.amount - amountNeeded
val nextHas = combineMaps(state.has.filterKeys { it != entry.key }, mapOf(entry.key to hasAmt))
return state.copy(needs = nextNeeds, has = nextHas)
}
fun combineMaps(baseMap: Map<String, Long>, additional: Map<String, Long>): Map<String, Long> =
(baseMap.asSequence() + additional.asSequence()).groupBy({ it.key }, { it.value }).mapValues { it.value.sum() }
fun parseInput(rawInput: String) =
rawInput.trimIndent().trim().split("\n")
.map { Reaction.parse(it) }
.map { it.output.name to it }.toMap()
data class ChemAmt(val name: String, val amount: Long) {
companion object {
fun parse(chemAmtStr: String): ChemAmt {
val info = chemAmtStr.split(" ")
return ChemAmt(name = info.last(), amount = info.first().toLong())
}
}
}
data class Reaction(val inputs: List<ChemAmt>, val output: ChemAmt) {
fun reactionsNeededToProduce(n: Long) = ceil(n.toDouble() / output.amount).toLong()
fun newNeeds(n: Long) = inputs.map { it.name to it.amount * n }.toMap()
companion object {
fun parse(reactionStr: String): Reaction {
val io = reactionStr.split(" => ")
val inputs = io.first().split(", ")
val output = io.last()
return Reaction(
inputs = inputs.map { ChemAmt.parse(it) },
output = ChemAmt.parse(output)
)
}
}
}
fun getInputReactions() = parseInput(
"""
10 LSZLT, 29 XQJK => 4 BMRQJ
22 HCKS => 1 GQKCZ
1 HCKS, 8 WZWRV, 18 HVZR => 7 BGFR
1 LSZLT, 1 WRKJ, 3 LJFP, 3 RNLPB, 1 NZGK, 3 LDSV, 5 RJDN, 8 HGFGC => 3 QZTXD
1 BRSGQ, 1 XGLF, 1 ZHSK, 20 LSZLT, 16 WFCPT, 3 KTWV, 1 QRJC => 4 XPKX
1 DCLR, 6 RNLPB => 5 HCKS
1 HFHFV => 3 SHLMF
2 LTMZQ, 21 FGCXN => 6 QKFKV
3 BGFR => 7 WRKJ
3 KHSB => 2 XQJL
3 SHLMF => 2 LPLG
12 SVHWT, 20 BXPSZ => 9 NBMF
2 FGCXN, 32 DCSVN => 8 TBDWZ
1 KHSB, 3 HGFGC => 6 WZWRV
27 WFCPT, 4 KTWV, 14 BRSGQ, 1 MFNK, 1 WRKJ, 2 NZGK, 24 FBFLK => 5 TRLCK
2 SVHWT => 3 QRJC
1 MNVR, 1 FKBMW => 2 FGCXN
4 GJXW => 9 JXFS
3 XQJK => 5 WNJM
1 WZVWZ, 1 XQJL => 9 SHKJV
2 DCSVN => 4 HDVC
2 GJXW => 2 RNLPB
1 QKFKV, 1 PBRWB => 5 WTZQ
14 QKFKV => 6 RDFTD
166 ORE => 1 QDSXV
2 DCSVN => 5 BXPSZ
113 ORE => 6 LTMZQ
13 MNVR => 7 RJDN
2 NZGK, 9 XQJK, 18 WRKJ => 9 KTWV
1 NZGK => 8 XQJK
6 RZCGN, 6 HDVC, 1 DLKR => 9 DSLXW
18 HVZR => 8 LJFP
7 XQJL => 1 NPDS
15 DLKR, 1 DSLXW, 26 MJFVP => 3 FBFLK
125 ORE => 9 MNVR
3 RJDN => 4 HFHFV
1 TBDWZ, 1 DCLR => 2 HVZR
2 SHKJV => 5 GJXW
7 LTMZQ, 1 QDSXV, 1 FKBMW => 3 DCSVN
9 LPLG, 11 JXFS => 3 BRSGQ
5 JXFS, 1 ZHSK, 25 XGLF => 4 MFNK
5 PBRWB => 2 SVHWT
15 SHKJV => 5 XGLF
1 XQJL, 2 NPDS => 4 DLKR
39 JXFS => 5 KSHF
6 GJXW, 1 FBFLK => 7 HGFGC
3 JXFS => 1 LSZLT
3 NBMF, 1 BMRQJ => 2 LDSV
1 JXFS, 25 GJXW, 10 HGFGC => 4 NZGK
8 QZTXD, 26 KSHF, 60 WNJM, 6 GJXW, 9 TRLCK, 20 XPKX, 21 FGCXN, 57 GQKCZ, 6 WRKJ => 1 FUEL
4 SVHWT, 1 RZCGN => 3 ZHSK
1 BXPSZ => 7 DCLR
8 RDFTD, 1 SHKJV, 1 HFHFV => 6 MJFVP
1 LTMZQ => 9 KHSB
5 WTZQ, 4 HGFGC, 4 HCKS => 9 WFCPT
184 ORE => 4 FKBMW
4 XQJL => 3 WZVWZ
12 QDSXV => 9 RZCGN
1 FBFLK, 7 HVZR => 9 PBRWB
""".trimIndent()
)
| 0 | Kotlin | 0 | 0 | 2283647e5b4ed15ced27dcf2a5cf552c7bd49ae9 | 6,572 | adventOfCode2019 | Apache License 2.0 |
src/Day18.kt | sitamshrijal | 574,036,004 | false | {"Kotlin": 34366} | fun main() {
fun parse(input: List<String>): List<Position3D> = input.map { Position3D.parse(it) }
fun part1(input: List<String>): Int {
val cubes = parse(input)
var count = 0
cubes.forEach { cube ->
count += 6 - cube.adjacentCubes().count { it in cubes }
}
return count
}
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.y } - 1..cubes.maxOf { it.z } + 1
val queue = mutableListOf(Position3D(xRange.first, yRange.first, zRange.first))
val visited = mutableSetOf<Position3D>()
var count = 0
while (queue.isNotEmpty()) {
val cube = queue.removeAt(0)
if (cube in visited) continue
visited += cube
cube.adjacentCubes().forEach {
if (it in cubes) {
count++
} else if (it.x in xRange && it.y in yRange && it.z in zRange) {
queue += it
}
}
}
return count
}
val input = readInput("input18")
println(part1(input))
println(part2(input))
}
data class Position3D(val x: Int, val y: Int, val z: Int) {
fun adjacentCubes(): List<Position3D> = listOf(
copy(x = x - 1),
copy(x = x + 1),
copy(y = y - 1),
copy(y = y + 1),
copy(z = z - 1),
copy(z = z + 1)
)
companion object {
fun parse(input: String): Position3D {
val (x, y, z) = input.split(",").map { it.toInt() }
return Position3D(x, y, z)
}
}
}
| 0 | Kotlin | 0 | 0 | fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d | 1,782 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | fun main() {
fun parseState(initial: String): MutableList<String> {
return initial.lines()
.dropLast(1)
.map { line ->
line.windowed(3, 4)
.map { if (it.trim().isEmpty()) "" else it[1].toString() }
}
.reduce { current, next ->
current.zip(next, String::plus)
}
.toMutableList()
}
fun solve(input: String, move: (state: MutableList<String>, from: Int, count: Int, to: Int) -> Unit): String {
val (initial, movesString) = input.split("\n\n")
val state = parseState(initial)
movesString.lines()
.map(String::extractNumbers)
.forEach { move(state, it[0], it[1] - 1, it[2] - 1) }
return state.map { it[0] }.joinToString(separator = "")
}
fun part1(input: String): String = solve(input) { state, count, from, to ->
val chunk = state[from].take(count).reversed()
state[from] = state[from].drop(count)
state[to] = chunk + state[to]
}
fun part2(input: String): String = solve(input) { state, count, from, to ->
val chunk = state[from].take(count)
state[from] = state[from].drop(count)
state[to] = chunk + state[to]
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 1,491 | Advent-of-Code-2022 | Apache License 2.0 |
2022/src/day12/day12.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day12
import GREEN
import RESET
import printTimeMillis
import readInput
import java.util.*
typealias Table = Array<Array<Point>>
data class Point(val value: Char, val minRisk: Int? = null)
data class Visit(val x: Int, val y: Int, val prev: Char, val currentRisk: Int)
fun Table.getValueOrNull(x: Int, y: Int, prev: Char): Char? {
if (x < 0 || y < 0 || y >= size || x >= this[y].size) return null // oob
if (this[y][x].value == 'E' && prev != 'z') return null // this is the end, but we didn't come from 'z'
if (this[y][x].value > prev + 1) return null // can climb to +1 letter or go down
return this[y][x].value
}
fun runDijkstra(table: Table, start: Pair<Int, Int>): Int? {
val toVisits: PriorityQueue<Visit> = PriorityQueue<Visit> { a, b ->
a.currentRisk - b.currentRisk
}.also { it.add(Visit(start.first, start.second, 'a', 0)) }
while (toVisits.isNotEmpty()) {
val curr = toVisits.remove()
val x = curr.x
val y = curr.y
val cumulatedRisk = curr.currentRisk + 1 // each step += 1 risk
val currMinRisk = table[y][x].minRisk
// We have visited this path and have already a risk lower than the current exploration
if (currMinRisk != null && currMinRisk <= cumulatedRisk) continue
table[y][x] = table[y][x].copy(minRisk = cumulatedRisk) // update the smallest risk for the cell
val currValue = table[y][x].value
if (currValue == 'E' && curr.prev == 'z') { // destination reached
return cumulatedRisk - 1
} else {
// add the next valid (non-null) paths to visit in an ordered stack
table.getValueOrNull(x + 1, y, currValue)?.let { toVisits.add(Visit(x + 1, y, currValue, cumulatedRisk)) } // right
table.getValueOrNull(x, y + 1, currValue)?.let { toVisits.add(Visit(x, y + 1, currValue, cumulatedRisk)) } // bottom
table.getValueOrNull(x - 1, y, currValue)?.let { toVisits.add(Visit(x - 1, y, currValue, cumulatedRisk)) } // left
table.getValueOrNull(x, y - 1, currValue)?.let { toVisits.add(Visit(x, y - 1, currValue, cumulatedRisk)) } // top
}
}
return null // no path found
}
fun part1(input: List<String>): Int? {
val start = input.indexOfFirst { it.contains("S") }.let {
Pair(input[it].indexOfFirst { it == 'S' }, it)
}
val newInput = input.map { it.map{ Point(it) }.toTypedArray() }.toTypedArray()
newInput[start.second][start.first] = newInput[start.second][start.first].copy(value = 'a')
return runDijkstra(newInput, start)
}
fun part2(input: List<String>): Int {
val start = input.indexOfFirst { it.contains("S") }.let {
Pair(input[it].indexOfFirst { it == 'S' }, it)
}
val newInput = input.map { it.map{ Point(it) }.toTypedArray() }.toTypedArray()
newInput[start.second][start.first] = newInput[start.second][start.first].copy(value = 'a')
val starts = newInput.flatMapIndexed { y, line ->
line.mapIndexed { x, c -> if (c.value == 'a') Pair(x, y) else null }.filterNotNull()
}
return starts.mapNotNull { runDijkstra(newInput, it) }.minOf { it }
}
fun main() {
val testInput = readInput("day12_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day12.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 3,586 | advent-of-code | Apache License 2.0 |
src/year2015/day14/Day14.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2015.day14
import check
import readInput
import java.lang.Integer.min
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2015", "Day14_test")
check(part1(testInput, 1000), 1120)
check(part2(testInput, 1000), 688)
val input = readInput("2015", "Day14")
println(part1(input, 2503))
println(part2(input, 2503))
}
private fun part1(input: List<String>, seconds: Int): Int {
return parseStatsByReindeer(input).maxOf { it.value.distanceAfter(seconds) }
}
private fun part2(input: List<String>, seconds: Int): Int {
val statsByReindeer = parseStatsByReindeer(input)
val scoresByReindeer = statsByReindeer.keys.associateWith { 0 }.toMutableMap()
for (s in 1..seconds) {
val winningReindeer = parseStatsByReindeer(input).maxBy { it.value.distanceAfter(s) }.key
scoresByReindeer[winningReindeer] = scoresByReindeer.getValue(winningReindeer) + 1
}
return scoresByReindeer.values.max()
}
private val pattern = "(\\w+) can fly (\\d+) km/s for (\\d+) seconds, but then must rest for (\\d+) seconds.".toRegex()
private fun parseStatsByReindeer(input: List<String>) = input.associate {
val (_, name, speed, time, restTime) = pattern.matchEntire(it)?.groupValues ?: error("Does not match pattern: $it")
name to Triple(speed.toInt(), time.toInt(), restTime.toInt())
}
private fun Triple<Int, Int, Int>.distanceAfter(seconds: Int): Int {
val (speed, time, restTime) = this
val cycles = seconds / (time + restTime)
val remainingTime = seconds % (time + restTime)
return cycles * speed * time + min(remainingTime, time) * speed
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,677 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/Day04.kt | NielsSteensma | 572,641,496 | false | {"Kotlin": 11875} | fun main() {
val input = readInput("Day04")
println("Day 04 Part 1 ${calculateDay04Part1(input)}")
println("Day 04 Part 2 ${calculateDay04Part2(input)}")
}
fun calculateDay04Part1(input: List<String>): Int {
return input.map(::getElvePairSections).count(::fullyOverlappingSections)
}
fun calculateDay04Part2(input: List<String>): Int {
return input.map(::getElvePairSections).count(::overlappingSections)
}
private fun getElvePairSections(value: String): Pair<IntRange, IntRange> {
// Split by dash. Given the input, first element in array is start of range and second is end of range.
fun getRangeOfSection(section: String) = section.split("-").let {
IntRange(it[0].toInt(), it[1].toInt())
}
val elvePair = value.split(",")
return Pair(getRangeOfSection(elvePair[0]), getRangeOfSection(elvePair[1]))
}
private fun fullyOverlappingSections(assigmentPair: Pair<IntRange, IntRange>): Boolean {
val firstElveSections = assigmentPair.first
val secondElveSections = assigmentPair.second
return secondElveSections.first >= firstElveSections.first && secondElveSections.last <= firstElveSections.last ||
firstElveSections.first >= secondElveSections.first && firstElveSections.last <= secondElveSections.last
}
private fun overlappingSections(assigmentPair: Pair<IntRange, IntRange>): Boolean {
val firstElveSections = assigmentPair.first
val secondElveSections = assigmentPair.second
var overlaps = false
for (section in firstElveSections) {
if (secondElveSections.contains(section)) {
overlaps = true
break
}
}
return overlaps
} | 0 | Kotlin | 0 | 0 | 4ef38b03694e4ce68e4bc08c390ce860e4530dbc | 1,667 | aoc22-kotlin | Apache License 2.0 |
advent-of-code2015/src/main/kotlin/day12/Advent12.kt | REDNBLACK | 128,669,137 | false | null | package day12
import parseInput
/**
--- Day 12: JSAbacusFramework.io ---
Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting software uses a peculiar storage format. That's where you come in.
They have a JSON document which contains a variety of things: arrays ([1,2,3]), objects ({"a":1, "b":2}), numbers, and strings. Your first job is to simply find all of the numbers throughout the document and add them together.
For example:
[1,2,3] and {"a":2,"b":4} both have a sum of 6.
[[[3]]] and {"a":{"b":4},"c":-1} both have a sum of 3.
{"a":[-1,1]} and [-1,{"a":1}] both have a sum of 0.
[] and {} both have a sum of 0.
You will not encounter any strings containing numbers.
What is the sum of all numbers in the document?
--- Part Two ---
Uh oh - the Accounting-Elves have realized that they double-counted everything red.
Ignore any object (and all of its children) which has any property with the value "red". Do this only for objects ({...}), not arrays ([...]).
[1,2,3] still has a sum of 6.
[1,{"c":"red","b":2},3] now has a sum of 4, because the middle object is ignored.
{"d":"red","e":[1,2,3,4],"f":5} now has a sum of 0, because the entire structure is ignored.
[1,"red",5] has a sum of 6, because "red" in an array has no effect.
*/
fun main(args: Array<String>) {
println(calculateSum("[1,2,3]") == 6)
println(calculateSum("""{"a":2,"b":4}""") == 6)
println(calculateSum("[[[3]]]") == 3)
println(calculateSum("""{"a":{"b":4},"c":-1}""") == 3)
println(calculateSum("""{"a":[-1,1]}""") == 0)
println(calculateSum("""[-1,{"a":1}]""") == 0)
println(calculateSum("""[]""") == 0)
println(calculateSum("""{}""") == 0)
val input = parseInput("day12-input.txt")
println(calculateSum(input))
println(calculateSumWithoutRed(input))
}
fun calculateSum(input: String) = Regex("""(-?\d+)""")
.findAll(input)
.map { it.groupValues[1] }
.map(String::toInt)
.sum()
fun calculateSumWithoutRed(input: String): Int {
val data = StringBuilder(input)
fun StringBuilder.findJsonDictBound(startPos: Int, endPos: Int): Int {
var counter = 0
var index = startPos
val map = mapOf('{' to 1, '}' to -1)
while (counter != endPos) {
index -= endPos
counter += map[this[index]] ?: 0
}
return index
}
while (true) {
val pos = data.indexOf(""":"red"""")
if (pos == -1) break
val start = data.findJsonDictBound(pos, 1)
val end = data.findJsonDictBound(pos, -1)
with (data) {
val add = StringBuilder(subSequence(0, start))
.append('0')
.append(subSequence(end + 1, data.length))
setLength(0)
append(add)
}
}
return calculateSum(data.toString())
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 2,899 | courses | MIT License |
src/Day10.kt | qmchenry | 572,682,663 | false | {"Kotlin": 22260} | fun main() {
data class RegisterState(val cycle: Int, val adjustment: Int)
fun cycleStates(input: List<String>): List<RegisterState> {
var cycle = 1
return input
.mapNotNull {
val instruction = it.split(" ")
when (instruction[0]) {
"noop" -> {
cycle += 1
null
}
"addx" -> {
cycle += 2
RegisterState(cycle, instruction[1].toInt())
}
else -> null
}
}
}
val keyCycles = listOf(20, 60, 100, 140, 180, 220)
fun part1(input: List<String>): Int {
val cycles = cycleStates(input)
val signals = keyCycles.map { keyCycle ->
val count = cycles
.takeWhile { cycle -> cycle.cycle <= keyCycle }
.sumOf { cycle -> cycle.adjustment }
println("keyCycle: $keyCycle, count: ${count + 1} = ${(count + 1) * keyCycle}")
(count + 1) * keyCycle
}
return signals.sum()
}
fun part2(input: List<String>): String {
val cycles = cycleStates(input)
val pixels = (0..239)
.map {
val position = 1 + cycles
.takeWhile { cycle -> cycle.cycle <= it }
.sumOf { cycle -> cycle.adjustment }
val pixel = if ((it % 40) in position - 0 .. position + 2) {
"#"
} else {
"-"
}
pixel
}
return pixels.chunked(40).map { it.joinToString("") }.joinToString("\n")
}
val testInput = readInput("Day10_sample")
check(part1(testInput) == 13140)
val realInput = readInput("Day10_input")
println("Part 1: ${part1(realInput)}")
println("Part 2: \n${part2(realInput)}")
}
| 0 | Kotlin | 0 | 0 | 2813db929801bcb117445d8c72398e4424706241 | 1,966 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/dr206/2022/Day05.kt | dr206 | 572,377,838 | false | {"Kotlin": 9200} | import java.util.Stack
fun main() {
fun createStacks(initialSate: List<String>): List<Stack<Char>> {
val stackShape = initialSate.filter { it.contains("[") }.reversed()
val numberOfStacks = (stackShape.first().length + 1) / 4
val stacks: List<Stack<Char>> = generateSequence { Stack<Char>() }.take(numberOfStacks).toMutableList()
val paddedShape = stackShape.map { it.padEnd(4 * numberOfStacks, ' ') }
for (idx in paddedShape.indices) {
for (i in 1..4 * numberOfStacks step 4) {
val char = paddedShape[idx][i]
if (char != ' ') stacks[i / 4].add(char)
}
}
return stacks
}
fun findTopOfStacks(
input: List<String>,
orderVariables: (Int, Int) -> Pair<Int, Int>
): String {
val (moves, initialSate) = input.partition { it.contains("move") }
val stacks: List<Stack<Char>> = createStacks(initialSate)
fun List<Stack<Char>>.print() = this.forEach { println(it.toString()) }
stacks.print()
for (move in moves) {
val (numberOfCratesToBeMoved, _, src, _, dest) = move.split(" ").subList(1, 6)
fun crateMovingProcess(timesCranePerformsALift: Int, cratesCraneMovesPerLift: Int) {
repeat(timesCranePerformsALift) {
(0 until cratesCraneMovesPerLift).fold(mutableListOf<Char>()) { acc, _ ->
acc.add(stacks[src.toInt() - 1].pop())
acc
}.reversed().onEach { stacks[dest.toInt() - 1].push(it) }
}
}
val (timesCranePerformsALift, cratesCraneMovesPerLift) = orderVariables(numberOfCratesToBeMoved.toInt(), 1)
crateMovingProcess(timesCranePerformsALift, cratesCraneMovesPerLift)
println("$numberOfCratesToBeMoved, _, $src, _, $dest")
stacks.print()
}
return String(stacks.map { it.pop() }.toCharArray())
.also { println("Result is: $it") }
}
fun part1(input: List<String>): String {
val identity = { a:Int, b:Int -> Pair(a, b) }
return findTopOfStacks(input, identity)
}
fun part2(input: List<String>): String {
val swap = { a:Int, b:Int -> Pair(b, a) }
return findTopOfStacks(input, swap)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println("Part 1 ${part1(input)}")
println("Part 2 ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 57b2e7227d992de87a51094a971e952b3774fd11 | 2,655 | advent-of-code-in-kotlin | Apache License 2.0 |
src/y2023/Day01.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2023
import util.readInput
import util.timingStatistics
val digitStrings = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
"1" to 1,
"2" to 2,
"3" to 3,
"4" to 4,
"5" to 5,
"6" to 6,
"7" to 7,
"8" to 8,
"9" to 9,
"0" to 0
)
val reverses = digitStrings.mapKeys { it.key.reversed() }
val re = Regex(
digitStrings.keys.joinToString(separator = "|")
)
val reReverse = Regex(
reverses.keys.joinToString(separator = "|")
)
val nonConsumingRe = Regex("(?=${re.pattern})")
object Day01 {
private fun parse(input: List<String>): List<Int> {
return input.map {
val ds = it.replace(Regex("[a-z]"), "")
(ds.first().toString() + ds.last().toString()).toInt()
}
}
fun part1(input: List<String>): Int {
val parsed = parse(input)
return parsed.sum()
}
private fun parse2(input: List<String>): List<Int> {
return input.map { line ->
val matches = nonConsumingRe.findAll(line)
val first = re.find(line, matches.first().range.first)
val last = re.find(line, matches.last().range.first)
digitStrings[first?.value]!! * 10 + digitStrings[last?.value]!!
}
}
fun part2(input: List<String>): Int {
val parsed = parse2(input)
return parsed.sum()
}
fun part2Faster(input: List<String>): Int {
val parsed = parseReverse(input)
return parsed.sum()
}
private fun parseReverse(input: List<String>): List<Int> {
return input.map { line ->
val matchFirst = re.find(line)
val matchLast = reReverse.find(line.reversed())
digitStrings[matchFirst?.value]!! * 10 + reverses[matchLast?.value]!!
}
}
}
fun main() {
val x = "3oneight"
val matches = re.findAll(x)
matches.forEach { println(it.value) }
val testInput = """
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
""".trimIndent().split("\n")
val testInput2 = """
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
""".trimIndent().split("\n")
println("------Tests------")
println(Day01.part1(testInput))
println(Day01.part2(testInput2))
println("------Real------")
val input = readInput("resources/2023/day01")
println("Part 1 result: ${Day01.part1(input)}")
println("Part 2 result: ${Day01.part2(input)}")
timingStatistics { Day01.part1(input) }
timingStatistics { Day01.part2(input) }
timingStatistics { Day01.part2Faster(input) }
}
val regexString = "one|two|three|four|five|six|seven|eight|nine|" + (1..9).joinToString("|")
val digits = regexString.split("|")
val regex = Regex(regexString)
fun codeGolfPart2() = println(
generateSequence(::readLine).map {
digits.indexOf(
regex.find(it)?.value
) % 9 * 10 + digits.indexOf(Regex(regex.pattern.reversed()).find(it.reversed())?.value?.reversed()) % 9
}.sum() + 11000
)
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 3,200 | advent-of-code | Apache License 2.0 |
src/Day07.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} |
interface Node {
val name: String
fun size(): Long
}
data class File(override val name: String, val size: Long): Node {
override fun size(): Long = size
}
data class Folder(override val name: String): Node {
private var children: Map<String, Node> = mutableMapOf()
private var size: Long? = null
override fun size(): Long {
if (size == null) {
this.size = children.values.sumOf { it.size() }
}
return size!!
}
fun childFolder(name: String): Folder = children[name] as Folder
fun initContent(children: List<Node>) {
this.children = children.associateBy { it.name }
}
fun smallFolders(): List<Folder> {
val result = children.values.filterIsInstance<Folder>().flatMap { it.smallFolders() }
if (size() <= 100000) {
return result + this
}
return result
}
fun findMinimallyLarger(atLeast: Long): Folder? {
if (this.size() < atLeast) {
return null
}
val folders = children.values.filterIsInstance<Folder>()
.mapNotNull { it.findMinimallyLarger(atLeast) }
return if (folders.isEmpty()) this else folders.minBy { it.size() }
}
}
interface Command {
val parameter: String?
}
data class Cd(override val parameter: String): Command
data class Ls(private val output: List<String>, override val parameter: String? = null): Command {
fun content(): List<Node> {
return output.map {
if (it.startsWith("dir")) Folder(it.substring("dir ".length))
else {
val split = it.split(" ")
File(split[1], split[0].toLong())
}
}
}
}
fun terminalOutput(output: List<String>): Iterable<Command> = Iterable {TerminalOutputIterator(output)}
class TerminalOutputIterator(private val output: List<String>): Iterator<Command> {
private var index = 0
override fun hasNext(): Boolean = index < output.size
override fun next(): Command {
val command = output[index++]
if (command.startsWith("$ cd")) {
return Cd(command.substring("$ cd ".length))
}
val lsOutput = mutableListOf<String>()
while(index < output.size && !output[index].startsWith("$")) {
lsOutput.add(output[index++])
}
return Ls(lsOutput)
}
}
fun main() {
fun restoreFs(input: List<String>): Folder {
val stack = mutableListOf<Folder>()
for (command in terminalOutput(input)) {
when(command) {
is Cd -> when (command.parameter) {
"/" -> stack.add(Folder("/"))
".." -> stack.removeLast()
else -> stack.add(stack.last().childFolder(command.parameter))
}
is Ls -> stack.last().initContent(command.content())
}
}
return stack.first()
}
fun part1(input: List<String>): Long {
return restoreFs(input).smallFolders().sumOf { it.size() }
}
fun part2(input: List<String>): Long {
val root = restoreFs(input)
val freeSpace = 70000000 - root.size()
val required = 30000000 - freeSpace
val folder: Folder = root.findMinimallyLarger(required)!!
return folder.size()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
check(part1(input) == 1783610L)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 3,650 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | private fun map(): List<CharArray> {
return readInput("Day12").map { it.toCharArray() }
}
private fun part1(map: List<CharArray>): Int {
val n = map.size
val m = map[0].size
val finish = find(map, 'E')
map[finish.y][finish.x] = 'z'
val start = find(map, 'S')
map[start.y][start.x] = 'a'
val visited = Array(n) { BooleanArray(m) }
var q = HashSet<C>()
q.add(start)
var curStep = 0
while (q.isNotEmpty()) {
val newQ = HashSet<C>()
q.forEach { cur ->
if (cur == finish) return curStep
visited[cur.y][cur.x] = true
val curC = map[cur.y][cur.x]
val left = C(cur.x - 1, cur.y)
if (check(left, n, m, visited) && (curC + 1 >= map[left.y][left.x])) {
newQ.add(left)
}
val right = C(cur.x + 1, cur.y)
if (check(right, n, m, visited) && (curC + 1 >= map[right.y][right.x])) {
newQ.add(right)
}
val up = C(cur.x, cur.y + 1)
if (check(up, n, m, visited) && (curC + 1 >= map[up.y][up.x])) {
newQ.add(up)
}
val down = C(cur.x, cur.y - 1)
if (check(down, n, m, visited) && (curC + 1 >= map[down.y][down.x])) {
newQ.add(down)
}
}
q = newQ
curStep++
}
return -1
}
private fun check(coord: C, n: Int, m: Int, visited: Array<BooleanArray>): Boolean {
val withinBounds = (coord.x in 0 until m) && (coord.y in 0 until n)
return withinBounds && !visited[coord.y][coord.x]
}
private fun find(map: List<CharArray>, c: Char): C {
for (i in map.indices) {
for (j in map[0].indices) {
if (map[i][j] == c) {
return C(j, i)
}
}
}
return C(-1, -1)
}
private fun part2(map: List<CharArray>): Int {
val n = map.size
val m = map[0].size
val start = find(map, 'E')
map[start.y][start.x] = 'z'
val visited = Array(n) { BooleanArray(m) }
var q = HashSet<C>()
q.add(start)
var curStep = 0
while (q.isNotEmpty()) {
val newQ = HashSet<C>()
q.forEach { cur ->
val curC = map[cur.y][cur.x]
if (curC == 'a') return curStep
visited[cur.y][cur.x] = true
val left = C(cur.x - 1, cur.y)
if (check(left, n, m, visited) && (curC - 1 <= map[left.y][left.x])) {
newQ.add(left)
}
val right = C(cur.x + 1, cur.y)
if (check(right, n, m, visited) && (curC - 1 <= map[right.y][right.x])) {
newQ.add(right)
}
val up = C(cur.x, cur.y + 1)
if (check(up, n, m, visited) && (curC - 1 <= map[up.y][up.x])) {
newQ.add(up)
}
val down = C(cur.x, cur.y - 1)
if (check(down, n, m, visited) && (curC - 1 <= map[down.y][down.x])) {
newQ.add(down)
}
}
q = newQ
curStep++
}
return -1
}
fun main() {
println(part1(map()))
println(part2(map()))
}
| 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 3,136 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day16/Day16.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day16
import PriorityQueue
import bfs
import execute
import parseRecords
import readAllText
data class Valve(val rate: Long, val exits: List<String>)
class Graph(valves: Map<String, Valve>) {
val data: List<Long>
val moves: Map<Pair<Int, Int>, Move>
val totalBits: Int
init {
var nextId = 1
val idToNumbers = valves.filter { (k, v) -> v.rate > 0 || k == "AA" }
.toList()
.sortedByDescending { it.second.rate }
.map { it.first }
.associateWith { if (it == "AA") 0 else nextId++ }
data = valves.filter { (k, v) -> v.rate > 0 || k == "AA" }
.map { (k, v) -> idToNumbers[k]!! to v.rate }
.sortedBy { it.first }
.map { it.second }
moves = valves
.filter { (k, v) -> v.rate > 0 || k == "AA" }
.keys.flatMap { s -> valves.filterValues { it.rate > 0 }.keys.map { e -> s to e } }
.filter { (s, e) -> s != e }
.associateWith { (s, e) ->
bfs(
graphOp = { p -> valves[p]!!.exits },
start = s,
initial = listOf<String>(),
moveOp = { l, p -> l + p },
endOp = { it == e }
)!!.let { Move(idToNumbers[e]!!, it.size) }
}
.mapKeys { (k, _) -> idToNumbers[k.first]!! to idToNumbers[k.second]!! }
totalBits = (1..data.lastIndex).sumOf { 1 shl it }
}
operator fun get(pos: Int): Long = data[pos]
}
data class Move(
val id: Int,
val dist: Int,
)
data class State(
val graph: Graph,
val timeLeft: Int,
val p1pos: Int = 0,
val p2pos: Int = 0,
val p1dist: Int = -1,
val p2dist: Int = -1,
val closed: Int = graph.totalBits,
val score: Long = 0,
) {
operator fun plus(actions: Pair<Move, Move>): State {
val (a1, a2) = actions
val timeElapsed = minOf(a1.dist, a2.dist).coerceAtLeast(1)
val newTileLeft = timeLeft - timeElapsed
var newScore = score
var newClosed = closed
if (a1.dist == 0) {
newScore += graph[a1.id] * newTileLeft
newClosed -= 1 shl a1.id
}
if (a2.dist == 0) {
newScore += graph[a2.id] * newTileLeft
newClosed -= 1 shl a2.id
}
return copy(
p1pos = a1.id,
p2pos = a2.id,
p1dist = a1.dist - timeElapsed,
p2dist = a2.dist - timeElapsed,
closed = newClosed,
timeLeft = newTileLeft,
score = newScore,
)
}
val potential: Long
get() = (1..graph.data.lastIndex)
.sumOf { if ((1 shl it) and this.closed > 0) graph.data[it] else 0 } * timeLeft
override fun toString() =
"@$p1pos($p1dist),$p2pos($p2dist), score $score, closed $closed, time left $timeLeft"
}
private fun State.possibleActions(): List<Pair<Move, Move>> = buildList {
if (timeLeft > 0) {
val ll1 = possibleForOne(p1pos, p1dist)
val ll2 = possibleForOne(p2pos, p2dist)
if (ll1.isNotEmpty() || ll2.isNotEmpty()) {
ll1.ifEmpty { listOf(Move(p1pos, 1)) }.forEach { l1 ->
ll2.ifEmpty { listOf(Move(p2pos, 1)) }.forEach { l2 ->
if (l1.id != l2.id) add(l1 to l2)
}
}
}
}
}
private fun State.possibleForOne(pos: Int, dist: Int) = buildList {
if (dist > 0) add(Move(pos, dist))
else if ((1 shl pos) and closed > 0) add(Move(pos, 0))
else {
val notCurr = (1..graph.data.lastIndex).filter { it != p1pos && it != p2pos && (1 shl it) and closed > 0 }
val next = notCurr.associateWith { t -> graph.moves[pos to t] ?: error("No path from $pos to $t") }
val reachable = next.filterValues { it.dist <= timeLeft }
reachable.forEach { (v, d) -> add(d) }
}
}
private fun search(graph: Graph, time: Int, players: Int): Long {
val start = State(graph, time, p2dist = if (players == 1) time * 2 else -1)
val comparator = compareByDescending<State> { it.score }
val queue = PriorityQueue(comparator).apply { offer(start) }
var result = 0L
while (queue.isNotEmpty()) {
val curr = queue.poll()
if (result < curr.score) {
result = curr.score
}
curr.possibleActions()
.map { curr + it }
.forEach { if (it.score + it.potential > result) queue.offer(it) }
}
return result
}
fun part1(input: String) = input.parseRecords(regex, ::parse)
.toMap()
.let { data -> search(Graph(data), 30, 1) }
fun part2(input: String) = input.parseRecords(regex, ::parse)
.toMap()
.let { data -> search(Graph(data), 26, 2) }
private val regex = "Valve (.+) has flow rate=(.+); tunnels? leads? to valves? (.+)".toRegex()
private fun parse(matchResult: MatchResult) =
matchResult.destructured.let { (a, b, c) -> a to Valve(b.toLong(), c.split(", ")) }
fun main() {
val input = readAllText("local/day16_input.txt")
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
""".trimIndent()
execute(::part1, test, 1651)
execute(::part1, input, 2359)
execute(::part2, test, 1707)
execute(::part2, input, 2999)
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 5,899 | advent-of-code-2022 | MIT License |
src/main/kotlin/day11.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package day11
import aoc.utils.*
import java.math.BigInteger
data class Monkey(
val index: Int,
var inspectionCount: Int,
val worryLevels: MutableList<BigInteger>,
val op: (BigInteger) -> BigInteger,
val divider: Int,
val successTarget: Int,
val failureTarget: Int
)
data class Move(val targetMonkey: Int, val worryLevel: BigInteger)
fun part1(): String {
return solve(20, 3)
}
fun part2(): String {
return solve(10000)
}
fun solve(rounds: Int, divider: Int? = null): String {
val monkeys =
readInput("day11-input.txt")
.windowed(6, 7)
.map { monkeyFromString(it) }
.associateBy { it.index }
val rootDivider = monkeys.values
.map { it.divider.toBigInteger() }
.reduce { acc, v -> acc * v }
repeat(rounds) {
(0..monkeys.size - 1).map { index ->
val monkey = monkeys[index]!!
val moves = monkey.worryLevels
.map { level ->
monkey.inspectionCount++
var newLevel = monkey.op.invoke(level)
if (divider != null)
newLevel = newLevel.divide(divider.toBigInteger())
else if (newLevel > rootDivider)
newLevel = newLevel.mod(rootDivider)
if (newLevel.mod(monkey.divider.toBigInteger()).equals(0.toBigInteger())) {
Move(monkey.successTarget, newLevel)
} else {
Move(monkey.failureTarget, newLevel)
}
}
monkey.worryLevels.clear()
moves.forEach {
monkeys[it.targetMonkey]!!.worryLevels.add(it.worryLevel)
}
}
}
val result = monkeys.values.sortedBy { it.inspectionCount }.reversed()
.take(2)
.map { it.inspectionCount.toBigInteger() }
.reduce { acc, v -> acc * v }
return result.toString();
}
private fun monkeyFromString(it: List<String>) = Monkey(
it[0].findFirstInt(),
0,
it[1].findInts().map { it.toBigInteger() }.toMutableList(),
operationFrom(it[2]),
testFromString(it[3]),
it[4].findFirstInt(),
it[5].findFirstInt(),
)
private fun testFromString(it: String): Int {
if (it.contains("divisible by")) return it.findFirstInt()
else throw Error("Unknown test $it")
}
fun operationFrom(input: String): (BigInteger) -> BigInteger {
val split = input.split(" ")
val leftOperand = split[5]
val rightOperand = split[7]
val operator = if (rightOperand == "old") "raise2" else split[6]
return if (leftOperand == "old") {
when (operator) {
"+" -> { a -> a + rightOperand.toBigInteger() }
"*" -> { a -> a * rightOperand.toBigInteger() }
"raise2" -> { a -> a * a }
else -> throw Error("unknown operator $operator")
}
} else {
throw Error("unknown left operand $leftOperand")
}
}
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 3,012 | adventOfCode2022 | Apache License 2.0 |
src/main/kotlin/Day2.kt | ummen-sherry | 726,250,829 | false | {"Kotlin": 4811} | import java.util.Locale
import java.util.Optional
import kotlin.jvm.optionals.getOrDefault
data class GameLimit(val redLimit: Int = 12, val greenLimit: Int = 13, val blueLimit: Int = 14)
fun GameLimit.isValid(color: String, count: Int): Boolean {
return when (color.lowercase(Locale.getDefault())) {
"red" -> this.redLimit >= count
"green" -> this.greenLimit >= count
"blue" -> this.blueLimit >= count
else -> false
}
}
private val gameLimit = GameLimit()
fun sumOfIDOfLegitGames(input: List<String>): Int {
return input.sumOf {
val limitExceededGameId = getLimitExceededGameId(it).getOrDefault(0)
limitExceededGameId
}
}
fun getLimitExceededGameId(gameInput: String): Optional<Int> {
val regex = Regex("Game (\\d+): (.*)")
val matchResult = regex.find(gameInput)
val groups = matchResult?.groupValues!!
val didLimitExceed = didLimitExceed(groups[1].toInt(), groups[2])
return if (!didLimitExceed) Optional.of(groups[1].toInt()) else Optional.empty<Int>()
}
fun didLimitExceed(gameId: Int, gameColorInput: String): Boolean {
val numberRegex = Regex("""(\d+) (\w+)""")
val numberMatches = numberRegex.findAll(gameColorInput)
numberMatches.forEach { matchResult ->
val groups = matchResult.groupValues
val count = groups[1].toInt()
val color = groups[2]
if (!gameLimit.isValid(color = color, count)) return true
}
return false
}
fun sumOfIDAndPowerOfLegitGames(input: List<String>): Int {
return input.sumOf {
val (gameId, power) = getMinPowerAndGameId(it)
if (gameId != 0) {
println("Game $gameId: Minimum Power = $power")
}
power
}
}
fun getMinPowerAndGameId(gameInput: String): Pair<Int, Int> {
val regex = Regex("Game (\\d+): (.*)")
val matchResult = regex.find(gameInput)
val groups = matchResult?.groupValues!!
val gameId = groups[1].toInt()
val minPower = calculateMinPower(groups[2])
return Pair(gameId, minPower)
}
fun calculateMinPower(gameColorInput: String): Int {
val numberRegex = Regex("""(\d+) (\w+)""")
val numberMatches = numberRegex.findAll(gameColorInput)
var maxRed = 1
var maxGreen = 1
var maxBlue = 1
for (matchResult in numberMatches) {
val groups = matchResult.groupValues
val count = groups[1].toInt()
val color = groups[2]
when (color) {
"red" -> maxRed = maxOf(maxRed, count)
"green" -> maxGreen = maxOf(maxGreen, count)
"blue" -> maxBlue = maxOf(maxBlue, count)
}
}
return maxRed * maxGreen * maxBlue
}
fun main(args: Array<String>) {
println("Advent 2023 - Day2")
val input = readFile("day-2-input1.txt")
// Part 1
// val sumOfIDOfLegitGames = sumOfIDOfLegitGames(input)
//
// println("Sum: $sumOfIDOfLegitGames")
// Part2
val sumOfIDAndPowerOfLegitGames = sumOfIDAndPowerOfLegitGames(input)
println("Sum: $sumOfIDAndPowerOfLegitGames")
} | 0 | Kotlin | 0 | 0 | c91c1b606a17a00e9efa5f2139d0efd0c1270634 | 3,040 | adventofcode2023 | MIT License |
src/Day07.kt | befrvnk | 574,229,637 | false | {"Kotlin": 15788} | sealed class Item {
abstract val name: String
abstract val size: Int
data class File(
override val name: String,
override val size: Int,
) : Item()
data class Directory(
override val name: String,
val items: MutableList<Item> = mutableListOf(),
val parent: Directory? = null,
) : Item() {
override val size: Int
get() = items.sumOf { it.size }
}
}
class Filesystem {
val root = Item.Directory("/")
private var current = root
fun cd(name: String) {
val nextDirectory = current.items.filterIsInstance<Item.Directory>().find { it.name == name }
current = when (name) {
".." -> current.parent!!
"/" -> root
else -> {
if (nextDirectory == null) {
val newDirectory = Item.Directory(name = name, parent = current)
current.items.add(newDirectory)
newDirectory
} else {
nextDirectory
}
}
}
}
fun dir(name: String) {
val directory = current.items.filterIsInstance<Item.Directory>().find { it.name == name }
if (directory == null) {
val newDirectory = Item.Directory(name = name, parent = current)
current.items.add(newDirectory)
}
}
fun file(name: String, size: Int) {
val file = current.items.filterIsInstance<Item.File>().find { it.name == name }
if (file == null) {
val newDirectory = Item.File(name, size)
current.items.add(newDirectory)
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val cd = Regex("\\$ cd (.*)")
val dir = Regex("dir (.*)")
val file = Regex("(\\d+) (.*)")
val filesystem = Filesystem()
input.forEach { line ->
cd.find(line)?.let { filesystem.cd(it.groupValues[1]) }
dir.find(line)?.let { filesystem.dir(it.groupValues[1]) }
file.find(line)?.let { filesystem.file(it.groupValues[2], it.groupValues[1].toInt()) }
}
fun Item.Directory.directorySizes(): List<Int> {
return listOf(size) + items.filterIsInstance<Item.Directory>()
.flatMap { it.directorySizes() }
}
return filesystem.root.directorySizes().filter { it <= 100_000 }.sum()
}
fun part2(input: List<String>): Int {
val cd = Regex("\\$ cd (.*)")
val dir = Regex("dir (.*)")
val file = Regex("(\\d+) (.*)")
val filesystem = Filesystem()
input.forEach { line ->
cd.find(line)?.let { filesystem.cd(it.groupValues[1]) }
dir.find(line)?.let { filesystem.dir(it.groupValues[1]) }
file.find(line)?.let { filesystem.file(it.groupValues[2], it.groupValues[1].toInt()) }
}
fun Item.Directory.directorySizes(): List<Int> {
return listOf(size) + items.filterIsInstance<Item.Directory>()
.flatMap { it.directorySizes() }
}
val missingSpace = 30_000_000 - (70_000_000 - filesystem.root.size)
return filesystem.root.directorySizes().filter { it >= missingSpace }.minOf { it }
}
// test if implementation meets criteria from the description, like:
// check(part1(testInput) == 7)
// check(part2(testInput) == "MCD")
val input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 68e5dd5656c052d8c8a2ea9e03c62f4cd2438dd7 | 3,508 | aoc-2022-kotlin | Apache License 2.0 |
src/day05/Code.kt | fcolasuonno | 572,734,674 | false | {"Kotlin": 63451, "Dockerfile": 1340} | package day05
import grouped
import readInput
data class BoxLocation(val layer: Int, val stackNumber: Int, val value: Char)
data class Movement(val amount: Int, val from: Int, val to: Int)
fun main() {
val format = """move (\d+) from (\d+) to (\d+)""".toRegex()
fun parse(input: List<String>) = input.map { it.ifEmpty { null } }.grouped().let { (cranes, movements) ->
val diagram = cranes.dropLast(1).flatMapIndexed { layer, boxes ->
boxes.withIndex().filter { it.value.isLetter() }.map { (index, value) ->
val stackNumber = ((index - 1) / 4) + 1
BoxLocation(layer, stackNumber, value)
}
}
val initialConfiguration = List(diagram.maxOf { it.stackNumber } + 1) { stackNumber ->
diagram.filter { it.stackNumber == stackNumber }.sortedBy { it.layer }.map { it.value }.toList()
}
val parsedMovements = movements.map { line ->
format.matchEntire(line)!!.destructured
.toList().map(String::toInt)
.let { (amount, from, to) ->
Movement(amount, from, to)
}
}
initialConfiguration to parsedMovements
}
fun part1(input: Pair<List<List<Char>>, List<Movement>>) = input.let { (initial, movements) ->
val configuration = initial.map { ArrayDeque(it) }
movements.forEach { (amount, from, to) ->
repeat(amount) {
configuration[to].add(0, configuration[from].removeFirst())
}
}
configuration.drop(1).joinToString("") { it.first().toString() }
}
fun part2(input: Pair<List<List<Char>>, List<Movement>>) = input.let { (initial, movements) ->
val configuration = initial.map { ArrayDeque(it) }
movements.forEach { (amount, from, to) ->
configuration[from].take(amount).reversed().forEach {
configuration[to].add(0, it)
}
repeat(amount) {
configuration[from].removeFirst()
}
}
configuration.drop(1).joinToString("") { it.first().toString() }
}
val input = parse(readInput(::main.javaClass.packageName))
println("Part1=\n" + part1(input))
println("Part2=\n" + part2(input))
}
| 0 | Kotlin | 0 | 0 | 9cb653bd6a5abb214a9310f7cac3d0a5a478a71a | 2,290 | AOC2022 | Apache License 2.0 |
src/day14/Day14.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | package day14
import kotlin.math.sign
import readInput
enum class Direction(val vec: Position) {
DOWN(Position(1, 0)),
DOWNLEFT(Position(1, -1)),
DOWNRIGHT(Position(1, 1)),
STAY(Position(0, 0))
}
data class Position(val row: Int, val column: Int) {
operator fun plus(other: Position): Position {
return Position(row + other.row, column + other.column)
}
operator fun minus(other: Position): Position {
return Position(row - other.row, column - other.column)
}
fun sign(): Position {
return Position(row.sign, column.sign)
}
}
fun next(sandUnit: Position, walls: Set<Position>, fallenSand: Set<Position>): Position? {
for (dir in Direction.values()) {
val possibleNext = sandUnit + dir.vec
if (!walls.contains(possibleNext) && !fallenSand.contains(possibleNext)) {
return possibleNext
}
}
return null
}
fun parsePosition(input: String): Position {
val (column, row) = input.split(",").map{ it.trim().toInt() }
return Position(row, column)
}
fun parseLine(input: String): List<Position> {
return input.split("->").map(::parsePosition)
}
fun getPostionsInBetween(start: Position, end: Position): List<Position> {
val ans = mutableListOf<Position>()
val vec = (end - start).sign()
var current = start + vec
while (current != end) {
ans.add(current)
current += vec
}
return ans
}
fun getLinePositions(line: List<Position>): List<Position> {
val ans = mutableListOf<Position>()
for (i in 0 .. line.size - 2) {
ans.add(line[i])
ans.addAll(getPostionsInBetween(line[i], line[i + 1]))
}
ans.add(line.last())
return ans
}
fun createWalls(lines: List<List<Position>>): Set<Position> {
return lines.flatMap { getLinePositions(it) }.toSet()
}
fun simulate(walls: Set<Position>): Int {
val startPosition = Position(0, 500)
val fallenSand = mutableSetOf<Position>()
val bottom = walls.maxOf { it.row }
while (true) {
var sandUnit = startPosition
var nextPos = next(sandUnit, walls, fallenSand)
while (nextPos != null && sandUnit != nextPos && nextPos.row <= bottom) {
sandUnit = nextPos
nextPos = next(sandUnit, walls, fallenSand)
}
if (nextPos == null || sandUnit.row == bottom) {
return fallenSand.size
}
fallenSand.add(sandUnit)
}
}
fun part1(input: List<String>): Int {
val walls = createWalls(input.map(::parseLine))
return simulate(walls)
}
fun part2(input: List<String>): Int {
val walls = createWalls(input.map(::parseLine))
val bottomRow = walls.maxOf { it.row + 2 }
val bottomLine = listOf(Position(bottomRow, -10000), Position(bottomRow, 10000))
return simulate(walls + createWalls(listOf(bottomLine)))
}
fun main() {
println("Day 14")
val testInput = readInput("Day14-test")
val input = readInput("Day14")
println("part 1 test: ${part1(testInput)}")
println("part 1 real: ${part1(input)}")
println("part 2 test: ${part2(testInput)}")
println("part 2 real: ${part2(input)}")
println()
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 3,166 | aoc-2022 | Apache License 2.0 |
src/Day11.kt | marosseleng | 573,498,695 | false | {"Kotlin": 32754} | fun main() {
fun part1(input: List<String>): Long {
val monkeys = parseMonkeys(input, manageWorryLevel = true)
play(monkeys, rounds = 20)
return monkeys
.sortedByDescending { it.inspects }
.take(2)
.fold(1) { acc, i -> acc * i.inspects }
}
fun part2(input: List<String>): Long {
val monkeys = parseMonkeys(input, manageWorryLevel = false)
play(monkeys, rounds = 10000)
return monkeys
.sortedByDescending { it.inspects }
.take(2)
.fold(1) { acc, i -> acc * i.inspects }
}
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
fun play(monkeys: List<AbstractMonkey>, rounds: Int) {
val commonMultiple = monkeys.fold(1L) { a, b -> a * b.divisor }
repeat(rounds) {
monkeys.forEach { monkey ->
monkey.inspectItems(commonMultiple).forEach { (item, monkey) ->
monkeys[monkey].addItem(item)
}
}
}
}
fun parseMonkeys(input: List<String>, manageWorryLevel: Boolean): List<AbstractMonkey> = input.chunked(7) { monkeyData ->
//Monkey 1:
val monkeyPosition = monkeyData[0].split(" ")[1].substringBefore(':').toInt()
// Starting items: 79, 60, 97
val startingItems = monkeyData[1].substringAfter("Starting items: ").split(", ").map { it.toLong() }
// Operation: new = old * 19
val operation: (Long, Long) -> Long
val operationMatched = """(.) (.+)""".toRegex()
.matchEntire(monkeyData[2].substringAfter("Operation: new = old "))
?.groupValues.orEmpty()
val sign = operationMatched[1].first()
val number = operationMatched[2].toLongOrNull()
when (sign) {
'+' -> {
operation = { a, b -> a + b }
}
'*' -> {
operation = { a, b -> a * b }
}
'-' -> {
operation = { a, b -> a - b }
}
'/' -> {
operation = { a, b -> a / b }
}
else -> {
operation = { a, _ -> a }
}
}
// Test: divisible by 23
val divisor = monkeyData[3].substringAfter("Test: divisible by ").toLong()
// If true: throw to monkey 2
val trueBranch = monkeyData[4].substringAfter("If true: throw to monkey ").toInt()
// If false: throw to monkey 3
val falseBranch = monkeyData[5].substringAfter("If false: throw to monkey ").toInt()
if (manageWorryLevel) {
Monkey(
index = monkeyPosition,
startingItems = startingItems,
operation = { operation(it, number ?: it) },
divisor = divisor,
trueIndex = trueBranch,
falseIndex = falseBranch
)
} else {
CongruenceMonkey(
index = monkeyPosition,
startingItems = startingItems,
operation = operation,
operationArgument = number,
divisor = divisor,
trueIndex = trueBranch,
falseIndex = falseBranch
)
}
}
abstract class AbstractMonkey(
val index: Int,
startingItems: List<Long>,
val divisor: Long,
private val trueIndex: Int,
private val falseIndex: Int,
) {
private val items = mutableListOf<Long>()
var inspects = 0L
private set
init {
items.addAll(startingItems)
}
protected fun getNextMonkey(value: Long): Int = if (value % divisor == 0L) trueIndex else falseIndex
abstract fun inspectSingleItem(inspectedItem: Long, maxCommonMultiple: Long): Pair<Long, Int>
fun addItem(item: Long) {
items.add(item)
}
fun inspectItems(maxCommonMultiple: Long): List<Pair<Long, Int>> {
val result = mutableListOf<Pair<Long, Int>>()
while (items.isNotEmpty()) {
val inspectedItem = items.removeFirst()
inspects++
result.add(inspectSingleItem(inspectedItem, maxCommonMultiple))
}
return result
}
override fun toString(): String {
return "Monkey[$index]: inspects:$inspects, items=${items.joinToString(prefix = "[", separator = ", ", postfix = "]")}"
}
}
class CongruenceMonkey(
index: Int,
startingItems: List<Long>,
val operation: (Long, Long) -> Long,
val operationArgument: Long?,
divisor: Long,
trueIndex: Int,
falseIndex: Int,
) : AbstractMonkey(index, startingItems, divisor, trueIndex, falseIndex) {
override fun inspectSingleItem(inspectedItem: Long, maxCommonMultiple: Long): Pair<Long, Int> {
val argument = operationArgument ?: inspectedItem
val preInspectionLevel = operation(inspectedItem, argument)
.mod(maxCommonMultiple)
return preInspectionLevel to getNextMonkey(preInspectionLevel)
}
}
class Monkey(
index: Int,
startingItems: List<Long>,
val operation: (Long) -> Long,
divisor: Long,
trueIndex: Int,
falseIndex: Int,
) : AbstractMonkey(index, startingItems, divisor, trueIndex, falseIndex) {
override fun inspectSingleItem(inspectedItem: Long, maxCommonMultiple: Long): Pair<Long, Int> {
val postInspectionLevel = operation(inspectedItem) / 3.toLong()
return postInspectionLevel to getNextMonkey(postInspectionLevel)
}
} | 0 | Kotlin | 0 | 0 | f13773d349b65ae2305029017490405ed5111814 | 5,417 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day21.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2020
import com.dvdmunckhof.aoc.splitOnce
class Day21(input: List<String>) {
private val foods = input.map { line ->
val (part1, part2) = line.splitOnce(" (contains ")
Food(part1.split(" "), part2.dropLast(1).split(", "))
}
fun solvePart1(): Int {
val allergenMap = getAllergenMap()
val allIngredients = foods.fold(listOf<String>()) { set, food -> set + food.ingredients }
val remainingIngredients = allergenMap.values.fold(allIngredients) { remainingIngredients, allergenIngredients ->
remainingIngredients - allergenIngredients
}
return remainingIngredients.size
}
fun solvePart2(): String {
val allergens = getAllergenMap().mapValues { it.value.toMutableSet() }
val ingredientStack = allergens.values.filter { it.size == 1 }.flatten().toMutableList()
while (ingredientStack.isNotEmpty()) {
val ingredient = ingredientStack.removeAt(0)
for (set in allergens.values.filter { it.size > 1 }) {
set.remove(ingredient)
if (set.size == 1) {
ingredientStack += set.first()
}
}
}
return allergens.toList().sortedBy { it.first }.joinToString(",") { it.second.first() }
}
private fun getAllergenMap(): Map<String, Set<String>> {
val allergenMap = mutableMapOf<String, Set<String>>()
for (food in foods) {
for (allergen in food.allergens) {
allergenMap[allergen] = if (allergenMap.containsKey(allergen)) {
allergenMap.getValue(allergen).intersect(food.ingredients)
} else {
food.ingredients.toSet()
}
}
}
return allergenMap
}
private data class Food(val ingredients: List<String>, val allergens: List<String>)
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,937 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch1/Problem14.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch1
import kotlin.math.log2
/**
* Problem 14: Longest Collatz Sequence
*
* https://projecteuler.net/problem=14
*
* Goal: Find the largest starting number <= N that produces the longest Collatz sequence.
*
* Constraints: 1 <= N <= 5e6
*
* Collatz Sequence: Thought to all finish at 1, a sequence of positive integers is generated
* using the hailstone calculator algorithm, such that:
* (even n) n -> n/2
* (odd n) n -> 3n + 1
*
* e.g.: N = 5
* 1
* 2 -> 1
* 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
* 4 -> 2 -> 1
* 5 -> 16 -> 8 -> 4 -> 2 -> 1
* longest chain when starting number = 3
*/
class LongestCollatzSequence {
private val limit = 5e6.toInt()
// cache for all previously counted collatz sequences
private val countedSeq = IntArray(limit + 1) { if (it == 0) 1 else 0 }
// cache for the starting number <= index that generates the longest sequence
private val longestCountedUnderN = IntArray(limit + 1) { if (it == 0) 1 else 0 }
/**
* Returns the largest starter that is <= [n], from a list of starters that stores the longest
* Collatz sequences.
*/
fun largestCollatzStarter(n: Int): Int = longestCountedUnderN[n - 1]
/**
* Returns the length of a Collatz sequence given its [start]ing number.
*/
fun collatzLength(start: Int): Int {
var count = 1
var prev = start
while (prev != 1) {
// if x AND 1 == 0 then x is even
prev = if (prev and 1 == 0) prev / 2 else prev * 3 + 1
// bitwise AND between positive x and x-1 will be zero if x is a power of 2
if (prev != 0 && (prev and (prev - 1) == 0)) {
count += log2(1.0 * prev).toInt() + 1
break
} else {
count++
}
}
return count
}
/**
* Generates all starting numbers < 5e6 that produce the longest sequence,
* [longestCountedUnderN].
*/
fun generateLongestStarters() {
var longestStarter = 1
var longestCount = 1
for (i in 2..limit) {
val currentLength = collatzLengthMemo(1L * i)
if (currentLength >= longestCount) {
longestStarter = i
longestCount = currentLength
}
longestCountedUnderN[i - 1] = longestStarter
}
}
/**
* Recursive solution uses saved lengths of previously determined Collatz sequences to speed
* performance of calling function.
*/
private fun collatzLengthMemo(start: Long): Int {
return if (start <= limit && countedSeq[start.toInt() - 1] != 0) {
countedSeq[start.toInt() - 1]
} else {
// if x AND 1 > 0 then x is odd
val count: Int = 1 + if (start and 1 > 0) {
// add a division by 2 as oddStart * 3 + 1 gives an even number,
// so both steps can be combined
collatzLengthMemo((3 * start + 1) / 2)
} else {
collatzLengthMemo(start / 2)
}
if (start <= limit) countedSeq[start.toInt() - 1] = count
count
}
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,230 | project-euler-kotlin | MIT License |
src/main/day09/day09.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day09
import Point
import kotlin.math.sign
import readInput
typealias Segment = Point
enum class Direction { R, U, D, L }
val regex = """([RUDL]) (\d+)""".toRegex()
val start = Segment(0, 0)
fun main() {
val input = readInput("main/day09/Day09")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
return input.toSteps().tailPositions(2).size
}
fun part2(input: List<String>): Int {
return input.toSteps().tailPositions(10).size
}
private fun List<Direction>.tailPositions(length: Int) =
tailPositions(Rope(Array(length) { Point(0, 0) }.toList()))
private fun List<Direction>.tailPositions(rope: Rope) = iterator().let { directions ->
generateSequence(rope) {
if (directions.hasNext()) it.step(directions.next())
else null
}.takeWhile { it != null }.map { it.tail() }.distinct().toList()
}
fun List<String>.toSteps(): List<Direction> {
val directions = mutableListOf<Direction>()
forEach {
regex.matchEntire(it)?.destructured?.let { (direction, steps) ->
repeat(steps.toInt()) {
directions.add(Direction.valueOf(direction))
}
} ?: error("invalid input")
}
return directions
}
data class Rope(val segments: List<Segment> = emptyList()) {
fun step(direction: Direction): Rope {
var newRope = Rope().add(head().move(direction))
segments.drop(1).forEach { segment ->
val head = newRope.tail()
newRope =
if (segment.isAdjacentTo(head)) newRope.add(segment)
else newRope.add(Segment((head.x - segment.x).sign + segment.x, (head.y - segment.y).sign + segment.y))
}
return newRope
}
private fun head() = segments.first()
fun tail(): Segment = segments.last()
private fun add(segment: Segment) = copy(segments = segments + segment)
}
fun Segment.isAdjacentTo(other: Segment): Boolean {
return other.x in (x - 1..x + 1) && other.y in (y - 1..y + 1)
}
fun Segment.move(direction: Direction) =
when (direction) {
Direction.R -> copy(x = x + 1)
Direction.U -> copy(y = y + 1)
Direction.D -> copy(y = y - 1)
Direction.L -> copy(x = x - 1)
} | 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 2,254 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day12.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package day12
import aoc.utils.*
import aoc.utils.graphs.Node
import aoc.utils.graphs.shortestDistance
import java.lang.Exception
data class Square(var height: Char, var isVisited: Boolean)
fun main() {
part2()
}
fun part1(): Long {
val map = Matrix(
readInput("day12-input.txt").map { it.toCharArray().toList() } )
val start = map.find { it == 'S' }!!
val end = map.find { it == 'E' }!!
map.replace(start,'a')
map.replace(end,'z')
val graphMatrix = buildFromMatrix(map){ relative, from, to ->
if(relative != Cursor(-1,-1)
&& relative != Cursor(-1,1)
&& relative != Cursor(1,-1)
&& relative != Cursor(1,1)
&& to <= from+1) {
1
} else null
}
val startNode = graphMatrix.get(start.cursor).value
val endNode = graphMatrix.get(end.cursor).value
return shortestDistance(startNode, endNode)!!
}
fun part2(): Long {
val map = Matrix(readInput("day12-input.txt")
.map { it.toList().map { Node(Square(it[0], false)) } })
val start = map.find { it.value.height == 'S' }!!
val end = map.find { it.value.height == 'E' }!!
start.value.value.height = 'a'
end.value.value.height = 'z'
buildGraph(map, start)
val anyShortest = map.findAll { it.value.value.height == 'a' }
.map {
try {
val foo = shortestDistance(it.value, end.value)!!
foo
} catch (e: Exception) {
// TODO shortest path should not error
10000
}
}
.minOf { it }
return anyShortest
}
/**
* Builds a graph form matrix with the idea that adjacent (also diagonal) entries can be connected.
* Will create a node for each element in the matrix.
* Will loop through the matrix and determined by the shouldLink predicate link nodes together.
* For example given a matrix of:
* "abc"
* "def",
* looking at "a" the shouldLink will be called with (notice the same elements in two ways):
* (a,b),(a,e),(a,d),(b,a),(e,a),(d,a)
*
* As a node is created for each element in matrix, multiple isolated graphs could be formed.
*
* The shouldLink returns the distance between nodes or null if there should not be a link.
* The relative position of the "to" node is given.
*/
fun <T> buildFromMatrix(matrix: Matrix<T>, distance: (relative: Cursor, from: T, to: T) -> Long?): Matrix<Node<T>> {
val nodeMatrix = matrix.map { Node(it.value) }
nodeMatrix.allInColumnOrder().forEach { thisNode ->
val neighbours = getSurrounding(nodeMatrix,thisNode)
neighbours.forEach { neighbour ->
val distance = distance(neighbour.cursor.minus(thisNode.cursor),thisNode.value.value, neighbour.value.value)
if(distance != null)
thisNode.value.link(distance, neighbour.value)
}
}
return nodeMatrix
}
private fun <T> getSurrounding(
matrix: Matrix<Node<T>>,
it: Entry<Node<T>>
) = matrix.getRelativeAt(
it.cursor,
listOf(
// Top
Cursor(-1, -1),
Cursor(0, -1),
Cursor(1, -1),
// Same line
Cursor(-1, 0),
Cursor(1, 0),
// Bottom
Cursor(-1, 1),
Cursor(0, 1),
Cursor(1, 1),
)
)
fun buildGraph(map: Matrix<Node<Square>>, current: Entry<Node<Square>>): Entry<Node<Square>> {
current.value.value.isVisited = true
val neighbours = map.getDirectNeighbours(current.cursor)
val accessible = neighbours
.filter { it.value.value.height <= current.value.value.height + 1 }
current.value.link(1, accessible.map { it.value })
accessible
.filter { !it.value.value.isVisited }
.forEach { buildGraph(map, it) }
return current
}
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 3,783 | adventOfCode2022 | Apache License 2.0 |
src/day13/Day13.kt | EndzeitBegins | 573,569,126 | false | {"Kotlin": 111428} | package day13
import day13.Fragment.CollectionFragment
import day13.Fragment.DataFragment
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.int
import readInput
import readTestInput
private data class Packet (
val fragments: CollectionFragment,
): Comparable<Packet> {
override fun compareTo(other: Packet): Int {
return this.fragments.compareTo(other.fragments)
}
}
private fun List<String>.toPacketPairs(): List<Pair<Packet, Packet>> {
return this.windowed(size = 2, step = 3) { (leftRawPacket, rightRawPacket) ->
leftRawPacket.toPacket() to rightRawPacket.toPacket()
}
}
private sealed interface Fragment {
data class DataFragment(val value: Int) : Fragment
data class CollectionFragment(val values: List<Fragment>) : Fragment
}
private fun String.toPacket(): Packet {
val parsedPacket: JsonArray = Json.decodeFromString(this)
return Packet(parsedPacket.toCollectionFragment())
}
private fun JsonArray.toCollectionFragment(): CollectionFragment {
val fragments = this.map { element ->
when (element) {
is JsonArray -> element.toCollectionFragment()
is JsonPrimitive -> DataFragment(element.int)
else -> error("Unsupported element type ${element::class.simpleName}!")
}
}
return CollectionFragment(fragments)
}
private fun Pair<Packet, Packet>.isOrdered(): Boolean {
val (lhs, rhs) = this
return lhs.fragments <= rhs.fragments
}
private operator fun Fragment.compareTo(rhs: Fragment): Int {
val lhs = this
if (lhs is DataFragment && rhs is DataFragment)
return lhs.value.compareTo(rhs.value)
val left = if (lhs is CollectionFragment) lhs.values else listOf(lhs)
val right = if (rhs is CollectionFragment) rhs.values else listOf(rhs)
for (index in 0..(left.lastIndex).coerceAtLeast(right.lastIndex)) {
when {
index > left.lastIndex && index <= right.lastIndex ->
return -1
index <= left.lastIndex && index > right.lastIndex ->
return 1
else -> {
val result = left[index].compareTo(right[index])
if (result != 0)
return result
}
}
}
return 0
}
private fun part1(input: List<String>): Int {
val packetPairs = input.toPacketPairs()
return packetPairs
.mapIndexed { index, packetPair -> if (packetPair.isOrdered()) index + 1 else 0 }
.sum()
}
private fun part2(input: List<String>): Int {
val packetPairs = input.toPacketPairs().flatMap { (lhs, rhs) -> listOf(lhs, rhs) }
val dividerPackets = listOf("[[2]]".toPacket(), "[[6]]".toPacket())
val allPackets = packetPairs + dividerPackets
val orderedPackets = allPackets.sorted()
return orderedPackets.mapIndexedNotNull { index, packet ->
if (packet in dividerPackets) {
index + 1
} else null
}.reduce { a, b -> a * b }
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day13")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebebdf13cfe58ae3e01c52686f2a715ace069dab | 3,424 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day9/SmokeBasin.kt | Arch-vile | 433,381,878 | false | {"Kotlin": 57129} | package day9
import utils.Cursor
import utils.Entry
import utils.Matrix
import utils.read
fun main() {
solve().let { println(it) }
}
val surroundingCoords = listOf(
Cursor(0, -1),
Cursor(-1, 0),
Cursor(1, 0),
Cursor(0, 1)
)
fun solve(): List<Int> {
val input = read("./src/main/resources/day9Input.txt")
.map { it.map { it.toString().toInt() } }
val floor = Matrix(input)
val lowestPoints = floor.all()
.filter { current ->
val surrounding = floor.getRelativeAt(
current.cursor,
surroundingCoords
)
val lowerNeighbours = surrounding
.filter { neighbor -> neighbor.value > current.value }
lowerNeighbours.count() == surrounding.count()
}
val basins = lowestPoints.map { basin(floor, it) }
val largestBasins = basins.sortedBy { it.size }.reversed().take(3)
return listOf(lowestPoints.map { it.value + 1 }.sum(),
largestBasins.map { it.size }.reduce { acc, next -> acc * next }
)
}
fun basin(floor: Matrix<Int>, start: Entry<Int>): Set<Entry<Int>> {
var expanded = setOf(start)
do {
var oldSize = expanded.size
expanded = expand(floor, expanded)
} while (expanded.size != oldSize)
return expanded;
}
fun expandSingle(floor: Matrix<Int>, startFrom: Entry<Int>): List<Entry<Int>> {
return floor.getRelativeAt(startFrom.cursor, surroundingCoords)
.filter { it.value > startFrom.value && it.value != 9 }
}
fun expand(floor: Matrix<Int>, current: Set<Entry<Int>>): Set<Entry<Int>> {
return current.map { expandSingle(floor, it) }.flatten().toSet().plus(current)
}
| 0 | Kotlin | 0 | 0 | 4cdafaa524a863e28067beb668a3f3e06edcef96 | 1,694 | adventOfCode2021 | Apache License 2.0 |
src/main/kotlin/aoc2021/Day03.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2021
import utils.InputUtils
fun main() {
val testInput = """00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010""".split("\n")
fun <K> Map<K, Int>.topKeyByValues() = if (values.size == values.toSet().size) {
this.keys.sortedByDescending { this[it] }.first()
} else {
null
}
fun <T> Iterable<T>.mostFrequent() = groupingBy { it }.eachCount().topKeyByValues()
fun not(c: Char): Char = ('1' + '0'.code - c).toChar()
fun swapBits(gamma: String) = gamma.map { not(it) }.joinToString("")
fun part1(input: List<String>): Int {
val gamma = input.asSequence()
.flatMap { digits ->
digits.mapIndexed { index, c -> IndexedValue(index, c) }
}
.groupBy({ it.index }, { it.value })
.map { it.key to it.value.mostFrequent() }
.sortedBy { it.first }
.map { it.second }.joinToString("")
val epsilon = swapBits(gamma)
println(gamma)
println(epsilon)
return gamma.toInt(2) * epsilon.toInt(2)
}
fun filtered(digit: Int, boolean: Boolean, items: List<String>): String {
val digits = items.map { it[digit] }
val mostFrequent = digits.mostFrequent() ?: '1'
val toMatch = if (boolean) mostFrequent else not(mostFrequent)
val matched = items.filter { it[digit] == toMatch }
return if (matched.size == 1) matched.first()
else filtered(digit + 1, boolean, matched)
}
fun part2(input: List<String>): Int {
val oxygenBits = filtered(0, true, input)
val co2Bits = filtered(0, false, input)
println(oxygenBits)
println(co2Bits)
return oxygenBits.toInt(2) * co2Bits.toInt(2)
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 198)
val puzzleInput = InputUtils.downloadAndGetLines(2021, 3)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 2,090 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day08.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2023
import eu.michalchomo.adventofcode.Day
import eu.michalchomo.adventofcode.main
object Day08 : Day {
override val number: Int = 8
override fun part1(input: List<String>): String = input.parseToMap().let { map: Map<String, Pair<String, String>> ->
val instructions = input[0]
solve(instructions, map, "AAA") { it == "ZZZ" }
}.toString()
override fun part2(input: List<String>): String = input.drop(2).mapNotNull { line ->
if ("A " in line) {
line.split(" ")[0]
} else null
}.let { endingWithA ->
val instructions = input[0]
val map = input.parseToMap()
endingWithA.map { solve(instructions, map, it) { it.last() == 'Z' } }.toList().lcm()
}.toString()
private fun solve(
instructions: String,
map: Map<String, Pair<String, String>>,
firstElement: String,
predicate: (String) -> Boolean
): Int {
var result = 0
var mutableFirstElement = firstElement
while (!predicate(mutableFirstElement)) {
val (steps, newLastElement) = instructions.fold(0 to mutableFirstElement) { (steps, node), instruction ->
val (left, right) = map[node]!!
val element = if (instruction == 'L') left else right
(steps + 1) to element
}
mutableFirstElement = newLastElement
result += steps
}
return result
}
private fun List<String>.parseToMap(): Map<String, Pair<String, String>> = this.drop(2).associate {
val nodeLeftRight = it.replace(" ", "").replace("(", "").replace(")", "")
.split('=', ',')
nodeLeftRight[0] to (nodeLeftRight[1] to nodeLeftRight[2])
}
private fun gcd(a: Long, b: Long): Long {
var a = a
var b = b
while (b != 0L) {
val temp = b
b = a % b
a = temp
}
return a
}
private fun lcm(a: Long, b: Long): Long {
return a * (b / gcd(a, b))
}
private fun List<Int>.lcm(): Long {
var result = this[0].toLong()
for (i in 1 until this.size) {
result = lcm(result, this[i].toLong())
}
return result
}
}
fun main() {
main(Day08)
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 2,328 | advent-of-code | Apache License 2.0 |
src/Day02.kt | MatthiasDruwe | 571,730,990 | false | {"Kotlin": 47864} | import java.lang.Error
fun main() {
fun part1(input: List<String>): Int {
val output = input.map { it.split(" ").map { it.convert() } }.sumOf {it[1].value + it[1].score(it[0]) }
return output
}
fun part2(input: List<String>): Int {
val output = input.map{convertToPair(it)}.sumOf { it.second.value + it.second.score(it.first) }
return output
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_example")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class Hand(val value: Int){
Rock(1), Paper(2), Scissors(3)
}
fun String.convert(): Hand{
return when(this){
"A", "X" -> Hand.Rock
"B", "Y" -> Hand.Paper
"C", "Z" -> Hand.Scissors
else -> throw Exception()
}
}
fun convertToPair(input: String): Pair<Hand, Hand>{
val items = input.split(" ")
val item1 = items[0].convert()
val item2 = when(items[1]){
"X" -> ((item1.value -1)%3).toHand()
"Y" -> item1
"Z" -> ((item1.value +1)%3).toHand()
else -> throw Exception()
}
return Pair(item1, item2)
}
fun Hand.score(opponent: Hand): Int{
if(this==opponent){
return 3
}
if((this.value+1)%3==opponent.value%3){
return 0
}
if((this.value-1)%3 == opponent.value%3){
return 6
}
return 0
}
fun Int.toHand(): Hand {
return when(this){
1 -> Hand.Rock
2-> Hand.Paper
0, 3-> Hand.Scissors
else -> throw Exception()
}
}
| 0 | Kotlin | 0 | 0 | f35f01cea5075cfe7b4a1ead9b6480ffa57b4989 | 1,674 | Advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day02.kt | julia-kim | 569,976,303 | false | null | package days
import readInput
fun main() {
// opponent plays - A for Rock, B for Paper, and C for Scissors
// you play - X for Rock, Y for Paper, and Z for Scissors
// total score: add up shape selected + outcome of the round score
// 1 for Rock, 2 for Paper, and 3 for Scissors
// 0 if you lost, 3 if the round was a draw, and 6 if you won
fun part1(input: List<String>): Int {
var totalScore = 0
// even is win, odd is draw
val moves = listOf("A Y", "A X", "B Z", "B Y", "C X", "C Z")
input.forEach { strategy ->
if (moves.contains(strategy)) {
if (moves.indexOf(strategy) % 2 == 0) {
totalScore += 6
} else totalScore += 3
}
val (_, myMove) = strategy.split(" ")
totalScore += when (myMove) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
}
return totalScore
}
fun String.toShapeScore(): Int {
return when (this) {
"A" -> 1
"B" -> 2
"C" -> 3
else -> 0
}
}
fun part2(input: List<String>): Int {
var totalScore = 0
// even is win, odd is loss
val moves = listOf("A B", "A C", "B C", "B A", "C A", "C B")
val myMoves = input.map { strategy ->
val (opponentsMove, outcome) = strategy.split(" ")
when (outcome) { // X means lose, Y means draw, and Z means win
"X" -> moves.last { it.take(1) == opponentsMove }.takeLast(1).toShapeScore()
"Y" -> {
totalScore += 3
opponentsMove.toShapeScore()
}
"Z" -> {
totalScore += 6
moves.first { it.take(1) == opponentsMove }.takeLast(1).toShapeScore()
}
else -> 0
}
}
totalScore += myMoves.sum()
return totalScore
}
// 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 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 2,352 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day4/Bingo.kt | Arch-vile | 433,381,878 | false | {"Kotlin": 57129} | package day4
import utils.Matrix
import utils.read
typealias Sheet = Matrix<Pair<Int, Boolean>>
fun main() {
solve().forEach { println(it) }
}
fun solve(): List<Any> {
val numbers = read("./src/main/resources/day4Input.txt")
.take(1)
.flatMap { it.split(",") }
.map { it.toInt() }
val sheets = read("./src/main/resources/day4Input.txt")
.drop(1)
.windowed(6, 6)
.map { rows ->
rows.drop(1)
.map { row ->
row.windowed(2, 3)
.map {
Pair(it.replace(" ", "").toInt(), false)
}
}
}
.map { Matrix(it) }
var nonWinningSheets = sheets.toMutableList()
var winningSheets = mutableListOf<Pair<Int,Sheet>>();
for (number in numbers) {
for (sheet in nonWinningSheets) {
val found = sheet.find(Pair(number, false))
if (found != null) {
sheet.replace(found, Pair(number, true))
val completedRows = sheet.keepRowsWithValues { entry -> entry.value.second }
val completedColumns = sheet.keepColumnsWithValues { entry -> entry.value.second }
if (completedRows.height() != 0 || completedColumns.height() != 0) {
winningSheets.add(Pair(number,sheet))
}
}
}
nonWinningSheets.removeAll(winningSheets.map { it.second })
}
return listOf(
calculateScore(winningSheets.first()),
calculateScore(winningSheets.last())
)
}
private fun calculateScore(sheet: Pair<Int, Sheet>): Int {
val sumOfMissedNmbr =
sheet.second.findAll { entry -> !entry.value.second }.map { it.value.first }.sum()
return sumOfMissedNmbr * sheet.first
}
| 0 | Kotlin | 0 | 0 | 4cdafaa524a863e28067beb668a3f3e06edcef96 | 1,837 | adventOfCode2021 | Apache License 2.0 |
src/Day11.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | fun main() {
data class Item(var worryLevel: Long)
class Monkey(
val monkeys: MutableList<Monkey>,
val items: ArrayDeque<Item>,
val operation: Pair<String, String>,
val testDivisibleBy: Int,
val trueTarget: Int,
val falseTarget: Int,
var inspectedItems: Int = 0,
) {
init {
monkeys += this
}
fun takeTurn(limitTo: Long, reduceBy: Long?) {
while (items.isNotEmpty()) {
val item = items.removeFirst()
inspectedItems++
val old = item.worryLevel
fun String.parseToLong() = when (this) {
"old" -> old
else -> this.toLong()
}
val (op, argument) = operation
var new = when (op) {
"+" -> old + argument.parseToLong()
"*" -> old * argument.parseToLong()
else -> error("Cannot execute $operation")
}
limitTo.let { new %= it }
reduceBy?.let { new /= it }
val target = if (new % testDivisibleBy == 0L) trueTarget else falseTarget
item.worryLevel = new
monkeys[target].items += item
}
}
}
fun List<String>.toMonkeys() = buildList {
this@toMonkeys.chunked(7).forEach { line ->
val monkey = line[0].removePrefix("Monkey ").removeSuffix(":").toInt()
check(monkey == size)
val startingItems = line[1].removePrefix(" Starting items: ").split(", ").map { it.toLong() }
val operation = line[2].removePrefix(" Operation: new = old ").split(" ").let { (op, arg) -> op to arg }
val test = line[3].removePrefix(" Test: divisible by ").toInt()
val ifTrue = line[4].removePrefix(" If true: throw to monkey ").toInt()
val ifFalse = line[5].removePrefix(" If false: throw to monkey ").toInt()
Monkey(
monkeys = this,
items = ArrayDeque(startingItems.map { Item(it) }),
operation = operation,
testDivisibleBy = test,
trueTarget = ifTrue,
falseTarget = ifFalse
)
}
}
/**
* We only care about the divisibility of the numbers, so we can reduce the number space to account for that.
* X mod N == 0
* (X mod L) mod N == 0
* given L divides cleanly by N
*/
fun List<Monkey>.calculateLimit() = map { it.testDivisibleBy }.product().toLong()
fun List<Monkey>.takeTurn(limitTo: Long, reduceBy: Long? = null) =
forEach { it.takeTurn(limitTo = limitTo, reduceBy = reduceBy) }
fun List<Monkey>.sumOfMonkeyBusiness() = map { it.inspectedItems.toLong() }.sortedDescending().take(2).product()
fun part1(input: List<String>): Long {
val monkeys = input.toMonkeys()
val limit = monkeys.calculateLimit()
repeat(20) {
monkeys.takeTurn(limitTo = limit, reduceBy = 3L)
}
return monkeys.sumOfMonkeyBusiness()
}
fun part2(input: List<String>): Long {
val monkeys = input.toMonkeys()
val limit = monkeys.calculateLimit()
repeat(10_000) {
monkeys.takeTurn(limitTo = limit)
}
return monkeys.sumOfMonkeyBusiness()
}
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 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 3,637 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day4/Day04.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package day4
fun solveA(input: List<String>) = input.count {
val pair = convertToRanges(it)
val intersection = pair.first.intersect(pair.second)
intersection.size == pair.first.count() || intersection.size == pair.second.count()
}
fun solveB(input: List<String>) = input.count {
val pair = convertToRanges(it)
pair.first.intersect(pair.second).isNotEmpty()
}
fun convertToRanges(input: String): Pair<IntRange, IntRange> {
val pair = input.split(",")
val first = pair.first().split("-").map { it.toInt() }
val firstRange = first.first()..first.last()
val second = pair.last().split("-").map { it.toInt() }
val secondRange = second.first()..second.last()
return Pair(firstRange, secondRange)
}
// First and actually faster Approach
//fun solveA(input: List<String>) = input.count {
// val pair = it.split(",")
// val first = pair.first().split("-").map { digit -> digit.toInt() }
// val second = pair.last().split("-").map { digit -> digit.toInt() }
//
// if (first.first() <= second.first() && first.last() >= second.last()) true
// else second.first() <= first.first() && second.last() >= first.last()
//}
//
//fun solveB(input: List<String>) = input.count {
// val pair = it.split(",")
// val first = pair.first().split("-").map { digit -> digit.toInt() }
// val second = pair.last().split("-").map { digit -> digit.toInt() }
//
// if (first.first() >= second.first() && first.first() <= second.last()) true
// else if (first.last() >= second.first() && first.last() <= second.last()) true
// else if (second.first() >= first.first() && second.first() <= first.last()) true
// else second.last() >= first.first() && second.last() <= first.last()
//}
| 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 1,736 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | private const val FIRST_OPPONENT_CODE = 'A'
private const val FIRST_SELF_CODE = 'X'
private const val LOSE_SCORE = 0
private const val DRAW_SCORE = 3
private const val WIN_SCORE = 6
enum class Shape(private val score: Int) {
ROCK(1) {
override val beats: Shape
get() = SCISSORS
},
PAPER(2) {
override val beats: Shape
get() = ROCK
},
SCISSORS(3) {
override val beats: Shape
get() = PAPER
};
fun playAgainst(other: Shape) = score + when(other) {
this -> DRAW_SCORE
beats -> WIN_SCORE
else -> LOSE_SCORE
}
abstract val beats: Shape
}
enum class RoundResult {
LOSE {
override fun calculateSelfShape(opponentShape: Shape) = opponentShape.beats
}, DRAW {
override fun calculateSelfShape(opponentShape: Shape) = opponentShape
}, WIN {
override fun calculateSelfShape(opponentShape: Shape) = Shape.values().first { it.beats == opponentShape }
};
abstract fun calculateSelfShape(opponentShape: Shape): Shape
}
fun main() {
fun play(input: List<String>, isPart1: Boolean) = input.sumOf {
val (opponentShapeCode, selfCode) = it.split(" ")
val opponentShape = Shape.values()[opponentShapeCode.first() - FIRST_OPPONENT_CODE]
val selfShape = if(isPart1) {
Shape.values()[selfCode.first() - FIRST_SELF_CODE]
} else {
RoundResult.values()[selfCode.first() - FIRST_SELF_CODE].calculateSelfShape(opponentShape)
}
selfShape.playAgainst(opponentShape)
}
fun part1(input: List<String>) = play(input = input, isPart1 = true)
fun part2(input: List<String>) = play(input = input, isPart1 = false)
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input)) // 15632
println(part2(input)) // 14416
}
| 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 1,956 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
src/day01/Day01.kt | k4vrin | 572,914,047 | false | {"Kotlin": 2480} | package day01
import readInput
import java.util.PriorityQueue
fun main() {
fun part1(input: String): Int {
return sumElfCalories(input).max()
}
fun part2(input: String): Int {
return sumElfCalories(input) caloriesOfTop 3
}
val testInput = readInput("day01", "Day01_test")
val input = readInput("day01", "Day01")
check(part1(testInput) == 24000)
println(part1(testInput))
println(part1(input))
check(part2(testInput) == 45000)
println(part2(testInput))
println(part2(input))
}
fun sumElfCalories(elvesCalories: String) =
elvesCalories.split("${System.lineSeparator()}${System.lineSeparator()}")
.map { elf ->
elf.lines()
.sumOf { it.toInt() }
}
infix fun List<Int>.caloriesOfTop(n: Int) =
// O(NLogN)
this.sortedDescending()
.take(n)
.sum()
// O(size * log size) -> O(size * log n)
infix fun List<Int>.lowerComplexityCaloriesOfTop(n: Int): Int {
// PriorityQueue for when we have two equal element
val best = PriorityQueue<Int>()
for (calories in this) {
best.add(calories)
if (best.size > n)
best.poll()
}
return best.sum()
}
fun List<Int>.linearCaloriesOfTop(n: Int): Int {
fun findTopN(n: Int, element: List<Int>): List<Int> {
if (element.size == n) return element
val x = element.random()
val small = element.filter { it < x }
val equal = element.filter { it == x }
val big = element.filter { it > x }
if (big.size >= n) return findTopN(n, big)
if (equal.size + big.size >= n) return (equal + big).takeLast(n)
return findTopN(n - equal.size - big.size, small) + equal + big
}
return findTopN(n, this).sum()
} | 0 | Kotlin | 0 | 1 | eb6495e86c35fa428500a137ea60fa4f58ff460f | 1,778 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch4/Problem49.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch4
import dev.bogwalk.util.combinatorics.permutationID
import dev.bogwalk.util.combinatorics.permutations
import dev.bogwalk.util.maths.isPrime
import dev.bogwalk.util.maths.primeNumbers
import kotlin.math.pow
/**
* Problem 49: Prime Permutations
*
* https://projecteuler.net/problem=49
*
* Goal: Return all concatenated numbers formed by joining K terms, such that the first term is
* below N and all K terms are permutations of each other, as well as being prime and in constant
* arithmetic progression.
*
* Constraints: 2000 <= N <= 1e6, K in {3, 4}
*
* e.g.: N = 2000, K = 3
* sequence = {1487, 4817, 8147}, with step = 3330
* output = "148748178147"
*/
class PrimePermutations {
/**
* Solution uses permutations() helper algorithm to find all permutations of a prime & filter
* potential candidates for a sequence.
*
* SPEED (WORSE) 64.91s for N = 1e6, K = 3
* Slower due to permutations being (re-)generated unnecessarily.
*/
fun primePermSequence(n: Int, k: Int): List<String> {
val primes = primeNumbers(n - 1)
val sequences = mutableListOf<String>()
for (first in primes) {
// there are no arithmetic sequences that match these properties with terms having
// less than 4 digits.
if (first < 1117) continue
val firstChars = first.toString().toList()
val perms = permutations(firstChars, firstChars.size)
.map{ it.joinToString("").toInt() }
.toSet()
.filter { perm ->
perm > first && perm.isPrime()
}
.sorted()
next@for (i in 0 until perms.size - k + 2) {
val second = perms[i]
val delta = second - first
for (x in 1..k-2) {
val next = second + x * delta
if (next !in perms.slice(i+1..perms.lastIndex)) {
continue@next
}
}
val sequence = List(k) { first + it * delta }
sequences.add(sequence.joinToString(""))
}
}
return sequences
}
/**
* Solution optimised by using permutationID() helper that maps all primes with same type and
* amount of digits to a permutation id. Then every list of primes that share a permutation
* id and has >= K elements is iterated over to check for an arithmetic progression sequence.
*
* Pre-generating all primes with same number of digits also eliminates the need to check for
* primality.
*
* SPEED (BETTER) 1.13s for N = 1e6, K = 3
*/
fun primePermSequenceImproved(n: Int, k: Int): List<String> {
val limit = (10.0).pow(n.toString().length).toInt() - 1
val primes = primeNumbers(limit)
val primePerms = mutableMapOf<String, List<Int>>()
val sequences = mutableListOf<List<Int>>()
for (prime in primes) {
if (prime < 1117) continue
val permID = permutationID(prime.toLong())
primePerms[permID] = primePerms.getOrDefault(permID, listOf()) + prime
}
for (perms in primePerms.values) {
if (perms.size >= k) {
for (i in 0 until perms.size - k + 1) {
val first = perms[i]
if (first >= n) break
next@for (j in i + 1 until perms.size - k + 2) {
val delta = perms[j] - first
for (x in 2 until k) {
val next = first + x * delta
if (next !in perms.slice(j+1..perms.lastIndex)) {
continue@next
}
}
sequences.add(List(k) { first + it * delta })
}
}
}
}
return sequences
.sortedBy { it.first() }
.map { it.joinToString("") }
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 4,094 | project-euler-kotlin | MIT License |
day-12/src/main/kotlin/PassagePathing.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | fun main() {
println("Part One Solution: ${partOne()}")
println("Part Two Solution: ${partTwo()}")
}
private fun partOne(): Int {
val map = readMap()
return getPaths(map, "start", mutableListOf(), false)
.count()
}
private fun partTwo(): Int {
val map = readMap()
return getPaths(map, "start", mutableListOf(), true)
.count()
}
private fun getPaths(
map: Map<String, List<String>>,
current: String,
visited: List<String>,
allowSingleSmallCaveTwice: Boolean
): List<List<String>> {
if (current == "end") {
return listOf(listOf(current))
}
val visitedNew = visited.toMutableList()
if (current.lowercase() == current) {
visitedNew.add(current)
}
val directions = map.entries
.filter { current in it.value }
.map { it.key }
.plus(map[current] ?: emptyList())
.filter { it != "start" }
val allowAlreadyVisited = allowSingleSmallCaveTwice && current !in visited
val result = directions
.filter { it !in visited || allowAlreadyVisited }
.flatMap {
getPaths(map, it, visitedNew, allowAlreadyVisited)
}
return result.map {
mutableListOf(current) + it
}
}
private fun readMap(): Map<String, List<String>> {
val map: MutableMap<String, MutableList<String>> = mutableMapOf()
readInputLines()
.forEach {
val split = it.split("-")
if (map[split[0]] != null) {
map[split[0]]!!.add(split[1])
} else {
map[split[0]] = mutableListOf(split[1])
}
}
return map
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 1,841 | aoc-2021 | MIT License |
grind-75-kotlin/src/main/kotlin/LowestCommonAncestorOfABinarySearchTree.kt | Codextor | 484,602,390 | false | {"Kotlin": 27206} | import commonclasses.TreeNode
/**
* Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
*
* According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
*
*
*
* Example 1:
*
*
* Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
* Output: 6
* Explanation: The LCA of nodes 2 and 8 is 6.
* Example 2:
*
*
* Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
* Output: 2
* Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
* Example 3:
*
* Input: root = [2,1], p = 2, q = 1
* Output: 2
*
*
* Constraints:
*
* The number of nodes in the tree is in the range [2, 10^5].
* -10^9 <= Node.val <= 10^9
* All Node.val are unique.
* p != q
* p and q will exist in the BST.
* @see <a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/">LeetCode</a>
*
* Definition for a binary tree node.
* class TreeNode(var `val`: Int = 0) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
return when {
root!!.`val` > p!!.`val` && root.`val` > q!!.`val` -> lowestCommonAncestor(root.left, p, q)
root.`val` < p.`val` && root.`val` < q!!.`val` -> lowestCommonAncestor(root.right, p, q)
else -> root
}
}
| 0 | Kotlin | 0 | 0 | 87aa60c2bf5f6a672de5a9e6800452321172b289 | 1,603 | grind-75 | Apache License 2.0 |
codeforces/kotlinheroes4/g.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes4
private fun solve(p: List<Int>, x: List<Int>): List<Int>? {
val k = (0..x.size - 3).minByOrNull { x[it + 2] - x[it] }
?: return listOf(x[0], p[0], x[1], p[0])
for (i in k..k + 2) for (j in k until i) for (aPeriod in p) {
val rem = x[i] % aPeriod
if (x[j] % aPeriod != rem) continue
val other = x.filter { it % aPeriod != rem }
val gcd = other.zipWithNext(Int::minus).fold(0, ::gcd)
val bPeriod = p.firstOrNull { gcd % it == 0 } ?: continue
val bPhase = ((other.firstOrNull() ?: 0) + bPeriod - 1) % bPeriod + 1
val aPhase = (rem + aPeriod - 1) % aPeriod + 1
return listOf(aPhase, aPeriod, bPhase, bPeriod)
}
return null
}
fun main() {
readLn()
val ans = solve(readInts(), readInts().sorted()) ?: return println("NO")
println("YES\n${ans[0]} ${ans[1]}\n${ans[2]} ${ans[3]}")
}
private tailrec fun gcd(a: Int, b: Int): Int = if (a == 0) b else gcd(b % a, a)
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,058 | competitions | The Unlicense |
src/main/kotlin/d21_DiracDice/DiracDice.kt | aormsby | 425,644,961 | false | {"Kotlin": 68415} | package d21_DiracDice
import util.Input
import util.Output
import kotlin.math.max
val possibleDiracRolls = mapPossibleRolls()
fun main() {
Output.day(21, "Dirac Dice")
val startTime = Output.startTime()
// region Part 1
val startPositions = Input.parseLines(filename = "/input/d21_start_positions.txt")
.map { it.substringAfter(": ").toInt() }
val roll = mutableListOf(98, 99, 100)
val players = listOf(
PlayerDeterministic(score = 0, position = startPositions[0]),
PlayerDeterministic(score = 0, position = startPositions[1])
)
var turn = 0
var nextPlayer = 0
do {
turn += 3
roll.next(3)
players[nextPlayer].play((roll.sum()))
nextPlayer = (nextPlayer + 1) % 2
} while (players.all { it.score < 1000 })
val loserProduct = players.first { it.score < 1000 }.score * turn
Output.part(1, "Deterministic Loser Product", loserProduct)
// endregion
// region Part 2
val diracPlayers = listOf(
PlayerDirac(startPosition = startPositions[0]),
PlayerDirac(startPosition = startPositions[1])
)
diracPlayers[0].play()
diracPlayers[1].play()
println(diracPlayers[0].lossMap)
println(diracPlayers[1].winMap)
val p1Wins = diracPlayers[0].winMap.map { it.value * diracPlayers[1].lossMap[it.key - 1]!! }.sum()
val p2Wins = diracPlayers[1].winMap.map { it.value * (diracPlayers[0].lossMap[it.key] ?: 0) }.sum()
Output.part(2, "Most Possible Wins", max(p1Wins, p2Wins))
// endregion
Output.executionTime(startTime)
}
class PlayerDeterministic(
var score: Int,
var position: Int
) {
private fun move(amount: Int) {
position = (position + amount) % 10
if (position == 0) position = 10
}
private fun addScore(amount: Int) {
score += amount
}
fun play(amount: Int) {
move(amount)
addScore(position)
}
}
fun MutableList<Int>.next(increase: Int) {
for (i in indices)
this[i] = (this[i] + increase) % 100
when (val i = indexOf(0)) {
-1 -> return
else -> this[i] = 100
}
}
// key = roll sum, value = num matching rolls
fun mapPossibleRolls(): Map<Int, Int> {
val rolls = mutableListOf(mutableListOf(1, 1, 1))
while (rolls.last().sum() != 9) {
val next = rolls.last().toMutableList()
next[2] += 1
if (next[2] > 3) {
next[2] = 1
next[1] += 1
}
if (next[1] > 3) {
next[1] = 1
next[0] += 1
}
rolls.add(next)
}
return rolls.groupingBy { it.sum() }.eachCount()
}
class PlayerDirac(
val startPosition: Int,
val winMap: MutableMap<Int, Long> = mutableMapOf(), //key=turn, value = numWins
val lossMap: MutableMap<Int, Long> = mutableMapOf()
) {
private fun scoreRollPermutation(rolls: List<Int>): Int {
var position = startPosition
var score = 0
rolls.forEach { r ->
position += r
if (position > 10)
position -= 10
score += position
}
return score
}
fun play() {
var rollSets = possibleDiracRolls.keys.map { mutableListOf(it) }.toMutableSet()
var turn = 1
while (rollSets.isNotEmpty()) {
// increment turn
turn++
// to store winning roll sets for removal
val turnWinSets = mutableSetOf<MutableList<Int>>()
// next permutation
val newRolls = mutableSetOf<MutableList<Int>>()
rollSets.forEach { prev ->
possibleDiracRolls.keys.forEach { poss ->
val curRoll = (prev + poss) as MutableList
newRolls.add(curRoll)
if (scoreRollPermutation(curRoll) > 20) {
addWinLoss(winMap, turn, curRoll)
turnWinSets.add(curRoll)
} else {
addWinLoss(lossMap, turn, curRoll)
}
}
}
rollSets = (newRolls - turnWinSets) as MutableSet
}
}
private fun addWinLoss(which: MutableMap<Int, Long>, turn: Int, rolls: List<Int>) {
val n = rolls.map { possibleDiracRolls[it]!! }.reduce { acc, cur -> acc * cur }.toLong()
which.merge(turn, n) { a, b -> a + b }
}
} | 0 | Kotlin | 1 | 1 | 193d7b47085c3e84a1f24b11177206e82110bfad | 4,422 | advent-of-code-2021 | MIT License |
src/day24/a/day24a.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day24.a
import copyClearForEach
import inFourDirections
import readInputLines
import shouldBe
import util.IntVector
import vec
fun main() {
val map = read()
val start = vec(1,0)
val end = map.bbox()[1]
val t = calculate(map, 0, start, end)
shouldBe(230, t)
}
fun calculate(map: Map, time: Int, start: IntVector, end: IntVector) : Int {
val w = map.width()
val h = map.height()-2
val reachable = HashSet<IntVector>()
reachable.add(start)
var t = time
do {
t++
map.clear()
for (b in map.blizzards) {
var p = b.initPos + b.velocity * t
p = vec( ((p[0]-1) % w + w) % w + 1, ((p[1]-1) % h + h) % h + 1 )
map.grid[p] = '*'
}
copyClearForEach(reachable) { p ->
if (map.grid[p] == '.') reachable.add(p)
inFourDirections { u ->
val q = p + u
if (map.grid[q] == '.') reachable.add(q)
}
}
} while (!reachable.contains(end))
return t
}
data class Blizzard(
val initPos : IntVector,
val velocity : IntVector,
)
class Map(
val grid: HashMap<IntVector, Char>
) {
val blizzards = ArrayList<Blizzard>()
init {
grid.forEach { (k,c) ->
val v = when(c) {
'<' -> vec(-1,0)
'>' -> vec(1,0)
'^' -> vec(0,-1)
'v' -> vec(0,1)
else -> null
}
if (v != null) blizzards.add(Blizzard(k, v))
}
clear()
}
fun clear() {
grid.iterator().forEach { it.setValue('.') }
}
fun print() {
val b = bbox()
for (y in b[0][1]..b[1][1]) {
for (x in b[0][0]..b[1][0])
print(grid[vec(x, y)] ?: ' ')
print('\n')
}
println('\n')
}
fun bbox(): Array<IntVector> {
val x1 = grid.keys.minOf { it[0] }
val y1 = grid.keys.minOf { it[1] }
val x2 = grid.keys.maxOf { it[0] }
val y2 = grid.keys.maxOf { it[1] }
return arrayOf(vec(x1, y1), vec(x2, y2))
}
fun width(): Int {
return bbox().let { it[1][0] - it[0][0] + 1 }
}
fun height(): Int {
return bbox().let { it[1][1] - it[0][1] + 1 }
}
}
fun read(): Map {
val m = HashMap<IntVector, Char>()
readInputLines(24)
.filter { it.isNotBlank() }
.forEachIndexed { y, line ->
for (x in line.indices) {
val c = line[x]
if (c != '#') {
m[vec(x, y)] = c
}
}
}
return Map(m)
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 2,652 | advent-of-code-2022 | Apache License 2.0 |
advent2022/src/main/kotlin/year2022/Day16.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2022
import AdventDay
class Day16 : AdventDay(2022, 16) {
data class ValveNode(
val name: String,
val flowRate: Int,
val neighbors: List<String>,
val distanceMap: MutableMap<String, Int> = mutableMapOf()
) {
companion object {
fun of(input: String): ValveNode = ValveNode(
input.drop(6).split(" has ")[0],
input.split(";")[0].split("=")[1].toInt(),
input.split("valves ", "valve ")[1].split(", ")
)
}
fun computeDistances(getNode: (String) -> ValveNode) = apply {
distanceMap[name] = 0
ArrayDeque<ValveNode>().let { queue ->
queue.add(this)
val visited = mutableSetOf<String>()
while (queue.isNotEmpty()) {
val current = queue.removeFirst()
val distance = current.distanceMap[name]!!
visited.add(current.name)
current.neighbors.filter { it !in visited }.forEach { n ->
val neighbor = getNode(n)
neighbor.distanceMap[name] = distance + 1
queue.addLast(neighbor)
}
}
}
distanceMap.remove(name)
}
}
private fun List<ValveNode>.computeAllDistances() = filter { it.flowRate > 0 }.forEach { r ->
r.computeDistances { node ->
this.first { it.name == node }
}
}
private operator fun List<ValveNode>.minus(other: Set<String>) = filter { it.name !in other }
private fun ValveNode.restOf(opened: Set<String>, timeLeft: Int) =
distanceMap.filter { (key, timeNeeded) -> key !in opened && timeNeeded + 1 <= timeLeft }
private fun List<ValveNode>.maxPath(opened: Set<String>, node: ValveNode, timeLeft: Int, sum: Int, open: Int): Int =
when {
timeLeft < 0 -> 0
timeLeft == 0 -> sum
node.restOf(opened, timeLeft).isEmpty() -> sum + timeLeft * open
else -> node.restOf(opened, timeLeft)
.map { (nNode, distance) ->
val nextNode = first { it.name == nNode }
maxPath(
opened + node.name,
nextNode,
timeLeft - (distance + 1),
sum + (distance + 1) * open,
open + nextNode.flowRate
)
}.plus(sum + timeLeft * open)
.max()
}
private fun allSelections(maximum: Int): Sequence<List<Int>> = sequence {
if (maximum == 0) {
yield(emptyList())
} else {
yieldAll(allSelections(maximum - 1).map { it + maximum })
yieldAll(allSelections(maximum - 1))
}
}
private fun List<ValveNode>.makeAllNonFlow(these: List<ValveNode>) = map { v ->
if (v in these) {
v.copy(flowRate = 0, distanceMap = mutableMapOf())
} else
v.copy(distanceMap = mutableMapOf())
}
private fun List<ValveNode>.partition(): Sequence<Pair<List<ValveNode>, List<ValveNode>>> {
val relevant = filter { it.flowRate > 0 }
return allSelections(relevant.size).map { ind ->
val listLeft = relevant.filterIndexed { i, _ -> i + 1 in ind }
val listRight = relevant - listLeft.toSet()
val left = makeAllNonFlow(listLeft)
val right = makeAllNonFlow(listRight)
left.computeAllDistances()
right.computeAllDistances()
left to right
}
}
private fun List<ValveNode>.maxPathWithElephantHelp(timeLeft: Int): Int = partition().map { (a, b) ->
val startNodeYou = a.first { it.name == "AA" }
val startNodeElephant = b.first { it.name == "AA" }
val you = a.maxPath(emptySet(), startNodeYou, timeLeft, 0, 0)
val elephant = b.maxPath(emptySet(), startNodeElephant, timeLeft, 0, 0)
you + elephant
}.max()
override fun part1(input: List<String>): Int {
val nodes = input.map { ValveNode.of(it) }
nodes.computeAllDistances()
val startNode = nodes.find { it.name == "AA" }!!
return nodes.maxPath(emptySet(), startNode, 30, 0, 0)
}
override fun part2(input: List<String>): Int {
val nodes = input.map { ValveNode.of(it) }
return nodes.maxPathWithElephantHelp(26)
}
}
fun main() = Day16().run() | 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 4,546 | advent-of-code | Apache License 2.0 |
src/Day22.kt | frungl | 573,598,286 | false | {"Kotlin": 86423} | import kotlin.math.max
import kotlin.math.min
enum class Direction {
UP, DOWN, LEFT, RIGHT;
private fun turnLeft() = when (this) {
UP -> LEFT
DOWN -> RIGHT
LEFT -> DOWN
RIGHT -> UP
}
private fun turnRight() = when (this) {
UP -> RIGHT
DOWN -> LEFT
LEFT -> UP
RIGHT -> DOWN
}
fun turn(direction: Direction) = when (direction) {
LEFT -> turnLeft()
RIGHT -> turnRight()
else -> throw IllegalArgumentException("Can only turn left or right")
}
fun toInt() = when (this) {
UP -> 3
DOWN -> 1
LEFT -> 2
RIGHT -> 0
}
}
data class GoInfo(val graph: Set<Pair<Int, Int>>, val rangesRow: Map<Int, Pair<Int, Int>>, val rangesCol: Map<Int, Pair<Int, Int>>)
data class NewSide(val v: Pair<Int, Int>, val d: Direction)
fun main() {
fun parseGraph(input: List<String>): GoInfo {
val set = mutableSetOf<Pair<Int, Int>>()
val rangesRow = mutableMapOf<Int, Pair<Int, Int>>()
val rangesCol = mutableMapOf<Int, Pair<Int, Int>>()
input.forEachIndexed { x, str ->
str.forEachIndexed { y, c ->
if (c == '.') {
set.add(Pair(x, y))
}
if (c != ' ') {
rangesRow[x] = rangesRow.getOrDefault(x, Pair(y, y)).let {
min(y, it.first) to max(y, it.second)
}
rangesCol[y] = rangesCol.getOrDefault(y, Pair(x, x)).let {
min(x, it.first) to max(x, it.second)
}
}
}
}
return GoInfo(set, rangesRow, rangesCol)
}
fun parsePath(path: String): List<Pair<Direction, Int>> {
var temp = path
val list = mutableListOf<Pair<Direction, Int>>()
var nowDir = Direction.RIGHT
while (temp.isNotEmpty()) {
val num = temp.takeWhile { it.isDigit() }.toInt()
temp = temp.dropWhile { it.isDigit() }
list.add(nowDir to num)
if (temp.isNotEmpty()) {
nowDir = when (temp.take(1)) {
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> throw IllegalArgumentException("Invalid input")
}
temp = temp.drop(1)
}
}
return list
}
fun part1(input: List<String>): Int {
val (graph, path) = input.filter { it.isNotEmpty() }.partition { !it[0].isDigit() }
val (graphSet, goRow, goCol) = parseGraph(graph)
val pathList = parsePath(path.single())
var v = graphSet.filter { it.first == 0 }.minBy { it.second }
var lastDir = Direction.UP
pathList.forEach {
val (dir, num) = it
lastDir = lastDir.turn(dir)
repeat(num) {
val next = when (lastDir) {
Direction.UP -> {
val (edgeUp, edgeDown) = goCol[v.second] ?: throw IllegalArgumentException("Column ranges is not found")
when (edgeUp <= v.first - 1) {
true -> v.first - 1
false -> edgeDown
} to v.second
}
Direction.DOWN -> {
val (edgeUp, edgeDown) = goCol[v.second] ?: throw IllegalArgumentException("Column ranges is not found")
when (edgeDown >= v.first + 1) {
true -> v.first + 1
false -> edgeUp
} to v.second
}
Direction.LEFT -> {
val (edgeLeft, edgeRight) = goRow[v.first] ?: throw IllegalArgumentException("Row ranges is not found")
v.first to when (edgeLeft <= v.second - 1) {
true -> v.second - 1
false -> edgeRight
}
}
Direction.RIGHT -> {
val (edgeLeft, edgeRight) = goRow[v.first] ?: throw IllegalArgumentException("Row ranges is not found")
v.first to when (edgeRight >= v.second + 1) {
true -> v.second + 1
false -> edgeLeft
}
}
}
v = when (graphSet.contains(next)) {
true -> next
false -> v
}
}
}
return (v.first + 1) * 1000 + (v.second + 1) * 4 + lastDir.toInt()
}
fun buildNextSide(): Map<Pair<Int, Int>, NewSide> {
val map = mutableMapOf<Pair<Int, Int>, NewSide>()
val a1 = (0..49).map { it to 150 }
val b1 = (100..149).map { NewSide(it to 99, Direction.LEFT) }.asReversed()
map.putAll(a1.zip(b1))
val a2 = (50..99).map { it to 100 }
val b2 = (100..149).map { NewSide(49 to it, Direction.UP) }
map.putAll(a2.zip(b2))
val a3 = (150..199).map { it to 50 }
val b3 = (50..99).map { NewSide(149 to it, Direction.UP) }
map.putAll(a3.zip(b3))
val a4 = (0..49).map { 200 to it }
val b4 = (100..149).map { NewSide(0 to it, Direction.DOWN) }
map.putAll(a4.zip(b4))
val a5 = (50..99).map { -1 to it }
val b5 = (150..199).map { NewSide(it to 0, Direction.RIGHT) }
map.putAll(a5.zip(b5))
val a6 = (0..49).map { 99 to it }
val b6 = (50..99).map { NewSide(it to 50, Direction.RIGHT) }
map.putAll(a6.zip(b6))
val a7 = (0..49).map { it to 49 }
val b7 = (100..149).map { NewSide(it to 0, Direction.RIGHT) }.asReversed()
map.putAll(a7.zip(b7))
val a8 = (100..149).map { it to 100 }
val b8 = (0..49).map { NewSide(it to 149, Direction.LEFT) }.asReversed()
map.putAll(a8.zip(b8))
val a9 = (100..149).map { 50 to it }
val b9 = (50..99).map { NewSide(it to 99, Direction.LEFT) }
map.putAll(a9.zip(b9))
val a10 = (50..99).map { 150 to it }
val b10 = (150..199).map { NewSide(it to 49, Direction.LEFT) }
map.putAll(a10.zip(b10))
val a11 = (100..149).map { -1 to it }
val b11 = (0..49).map { NewSide(199 to it, Direction.UP) }
map.putAll(a11.zip(b11))
val a12 = (150..199).map { it to -1 }
val b12 = (50..99).map { NewSide(0 to it, Direction.DOWN) }
map.putAll(a12.zip(b12))
val a13 = (50..99).map { it to 49 }
val b13 = (0..49).map { NewSide(100 to it, Direction.DOWN) }
map.putAll(a13.zip(b13))
val a14 = (100..149).map { it to -1 }
val b14 = (0..49).map { NewSide(it to 50, Direction.RIGHT) }.asReversed()
map.putAll(a14.zip(b14))
return map
}
fun part2(input: List<String>): Int {
val (graph, path) = input.filter { it.isNotEmpty() }.partition { !it[0].isDigit() }
val graphSet = parseGraph(graph).graph
val pathList = parsePath(path.single())
val nextSide = buildNextSide()
var v = graphSet.filter { it.first == 0 }.minBy { it.second }
var lastDir = Direction.UP
pathList.forEach {
val (dir, num) = it
lastDir = lastDir.turn(dir)
repeat(num) {
val maybeNext = when (lastDir) {
Direction.UP -> v.first - 1 to v.second
Direction.DOWN -> v.first + 1 to v.second
Direction.LEFT -> v.first to v.second - 1
Direction.RIGHT -> v.first to v.second + 1
}
val (nextV, nextDir) = if (nextSide.containsKey(maybeNext)) {
Pair(
nextSide[maybeNext]?.v ?: throw IllegalArgumentException("Point is not found"),
nextSide[maybeNext]?.d ?: throw IllegalArgumentException("Direction is not found")
)
} else {
maybeNext to lastDir
}
if (graphSet.contains(nextV)) {
v = nextV
lastDir = nextDir
}
}
}
return (v.first + 1) * 1000 + (v.second + 1) * 4 + lastDir.toInt()
}
val testInput = readInput("Day22_test")
check(part1(testInput) == 6032)
// check(part2(testInput) == 0)
val input = readInput("Day22")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d4cecfd5ee13de95f143407735e00c02baac7d5c | 8,642 | aoc2022 | Apache License 2.0 |
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day11.kt | loehnertz | 573,145,141 | false | {"Kotlin": 53239} | package codes.jakob.aoc
import codes.jakob.aoc.shared.multiply
import codes.jakob.aoc.shared.parseInt
import codes.jakob.aoc.shared.splitMultiline
class Day11 : Solution() {
override fun solvePart1(input: String): Any {
val monkeys: List<Monkey> = input.split("\n\n").map { parseMonkey(it) }
val worryDecrease: (Long) -> Long = { level -> level / 3 }
return calculateMonkeyBusinessLevel(monkeys, 20, worryDecrease)
}
override fun solvePart2(input: String): Any {
val monkeys: List<Monkey> = input.split("\n\n").map { parseMonkey(it) }
val lowestCommonMultiple: Int = monkeys.map { it.test.divideBy }.multiply()
val worryDecrease: (Long) -> Long = { level -> level % lowestCommonMultiple }
return calculateMonkeyBusinessLevel(monkeys, 10000, worryDecrease)
}
private fun calculateMonkeyBusinessLevel(
monkeys: Collection<Monkey>,
rounds: Int,
worryDecrease: (Long) -> Long,
): Long {
val monkeysById: Map<Int, Monkey> = monkeys.associateBy { it.id }
val monkeyInspections: MutableMap<Monkey, Long> = mutableMapOf<Monkey, Long>().withDefault { 0 }
repeat(rounds) {
for (monkey: Monkey in monkeysById.values) {
for (item: Long in monkey.items.toList()) {
// Inspect
val newItem: Long = worryDecrease(monkey.operation(item))
monkeyInspections[monkey] = monkeyInspections.getValue(monkey) + 1
// Test
val nextMonkey: Monkey = if (monkey.test.check(newItem)) {
monkeysById.getValue(monkey.test.ifTrue)
} else {
monkeysById.getValue(monkey.test.ifFalse)
}
// Pass on
monkey.items.remove(item).also { nextMonkey.items.add(newItem) }
}
}
}
return monkeyInspections.values.sortedDescending().take(2).multiply()
}
private fun parseMonkey(toParse: String): Monkey {
val lines: List<String> = toParse.splitMultiline()
val id: Int = lines[0].substringAfter(" ").first().parseInt()
val items: List<Long> = lines[1].substringAfter(": ").split(", ").map { it.toLong() }
val operation: (Long) -> Long = parseOperation(lines[2].substringAfter("old "))
val test: Test = parseTest(lines[3].substringAfter(": "), lines[4], lines[5])
return Monkey(id, items.toMutableList(), operation, test)
}
private fun parseOperation(toParse: String): (Long) -> Long {
val (sign, number) = toParse.split(" ")
return when (sign) {
"+" -> if (number == "old") { old -> old + old } else { old -> old + number.toInt() }
"-" -> if (number == "old") { old -> old - old } else { old -> old - number.toInt() }
"*" -> if (number == "old") { old -> old * old } else { old -> old * number.toInt() }
"/" -> if (number == "old") { old -> old / old } else { old -> old / number.toInt() }
else -> error("Unknown sign: $sign")
}
}
private fun parseTest(toParse: String, ifTrueMonkey: String, ifFalseMonkey: String): Test {
val divisibleBy: Int = toParse.substringAfterLast(" ").toInt()
return Test(
{ level -> level % divisibleBy == 0L },
divisibleBy,
ifTrueMonkey.last().parseInt(),
ifFalseMonkey.last().parseInt(),
)
}
data class Monkey(
val id: Int,
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: Test,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Monkey) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id
}
override fun toString(): String {
return "Monkey(id=$id)"
}
}
data class Test(
val check: (Long) -> Boolean,
val divideBy: Int,
val ifTrue: Int,
val ifFalse: Int,
)
}
fun Collection<Long>.multiply(): Long = reduce { acc, l -> acc * l }
fun main() = Day11().solve()
| 0 | Kotlin | 0 | 0 | ddad8456dc697c0ca67255a26c34c1a004ac5039 | 4,333 | advent-of-code-2022 | MIT License |
src/Day02.kt | pavlov200912 | 572,885,762 | false | {"Kotlin": 3267} | fun main() {
fun transformMove(move: String): Int {
return when (move) {
"A" -> 0 // rock
"B" -> 1 // paper
"C" -> 2 // scissors
"X" -> 0
"Y" -> 1
"Z" -> 2
else -> {
-1
}
}
}
fun movePrize(move: Int): Int {
return move + 1
}
fun findMyMove(otherMove: Int, result: String): Int {
if (result == "Y") return otherMove
if (result == "Z") {
return when (otherMove) {
0 -> 1
1 -> 2
2 -> 0
else -> -1
}
}
return when (otherMove) {
0 -> 2
1 -> 0
2 -> 1
else -> -1
}
}
fun playMoves(move1: Int, move2: Int): Int {
if (move1 == move2) return 3
if (move1 == 0 && move2 == 1) return 6
if (move1 == 1 && move2 == 2) return 6
if (move1 == 2 && move2 == 0) return 6
return 0
}
fun part1(input: List<String>): Int {
return input.map {
val split = it.split(" ")
val move1 = transformMove(split[0])
val move2 = transformMove(split[1])
// println(playMoves(move1, move2).toString() + " " + movePrize(move2))
playMoves(move1, move2) + movePrize(move2)
}.sum()
}
fun part2(input: List<String>): Int {
return input.map {
val split = it.split(" ")
val move1 = transformMove(split[0])
val game = split[1]
val move2 = findMyMove(move1, game)
// println(move1.toString() + " " + move2.toString() + " " + playMoves(move1, move2).toString() + " " + movePrize(move2))
playMoves(move1, move2) + movePrize(move2)
}.sum()
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cef9f2d0a5ec231801fa85dfbd92c0e7ee86eddf | 1,950 | aoc-2022 | Apache License 2.0 |
src/Day16.kt | SnyderConsulting | 573,040,913 | false | {"Kotlin": 46459} | import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicInteger
fun main() {
fun part1(input: List<String>): Int {
val spaces = input.map { Space.from(it) }
val distanceMap = spaces.map { it.name to it.getOtherDistances(spaces) }
val startingSpace = spaces.find { it.name == "AA" }!!
val valveOptions = spaces.filter { it.flowRate > 0 }
val paths = getPathPermutations(startingSpace, valveOptions, distanceMap, 30)
return paths.maxOf { it.second }
}
fun part2(input: List<String>): Int {
val spaces = input.map { Space.from(it) }
val distanceMap = spaces.map { it.name to it.getOtherDistances(spaces) }
val startingSpace = spaces.find { it.name == "AA" }!!
val valveOptions = spaces.filter { it.flowRate > 0 }
val myPaths = getPathPermutations(startingSpace, valveOptions, distanceMap, 26)
val bestScore = AtomicInteger()
runBlocking {
withContext(Dispatchers.Default) {
myPaths.forEachIndexed { idx, path ->
launch {
println("Best score: ${bestScore.get()} ($idx / ${myPaths.size})")
getPathPermutations(startingSpace, valveOptions, distanceMap, 26, path.first).forEach {
if (path.second + it.second > bestScore.get()) {
bestScore.set(path.second + it.second)
println("New best score: (${path.second + it.second}) ${path.first} ${it.first} ")
}
}
}
}
}
}
return bestScore.get()
}
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
fun getPathPermutations(
startingSpace: Space,
spaces: List<Space>,
distanceMap: List<Pair<String, List<Pair<String, Int>>>>,
time: Int,
visitedSpaces: List<String> = listOf()
): List<Pair<List<String>, Int>> {
val permutations = mutableListOf<Pair<List<String>, Int>>()
fun getAllPaths(
pathHead: Space,
currentPath: Pair<List<String>, Int>,
minutesRemaining: Int
): Set<Pair<List<String>, Int>> {
val remainingSpaces = spaces.filter {
!visitedSpaces.contains(it.name) && !currentPath.first.contains(it.name) && minutesRemaining >= (distanceMap.distanceBetween(
pathHead.name,
it.name
) + 1)
}
return if (remainingSpaces.isNotEmpty()) {
remainingSpaces.flatMap {
getAllPaths(
it,
Pair(
currentPath.first.plus(it.name),
currentPath.second + ((minutesRemaining - (distanceMap.distanceBetween(
pathHead.name,
it.name
) + 1)) * it.flowRate)
),
minutesRemaining - (distanceMap.distanceBetween(pathHead.name, it.name) + 1)
).plus(setOf(currentPath))
}.toSet()
} else setOf(currentPath)
}
val allPaths = getAllPaths(startingSpace, Pair(emptyList(), 0), time)
permutations.addAll(allPaths)
return permutations
}
private fun List<Pair<String, List<Pair<String, Int>>>>.distanceBetween(source: String, destination: String): Int {
return find { key -> key.first == source }?.second?.find { it.first == destination }?.second!!
}
data class Space(
val name: String,
val flowRate: Int,
val connections: List<String>
) {
fun getOtherDistances(spaces: List<Space>): List<Pair<String, Int>> {
val currentSpace = Pair(name, 0)
val otherDistances = mutableListOf(currentSpace)
fun getNestedDistances(key: String, distance: Int): List<Pair<String, Int>> {
val space = spaces.find { it.name == key }!!
space.connections.forEach { connection ->
val x = otherDistances.find { connection == it.first }
if (x != null) {
if (distance < x.second) {
otherDistances.remove(x)
}
}
}
val unmappedDistances = space.connections.filter { connection ->
otherDistances.none { connection == it.first }
}
return if (unmappedDistances.isNotEmpty()) {
otherDistances.addAll(unmappedDistances.map { it to distance })
unmappedDistances.flatMap { getNestedDistances(it, distance + 1) }
} else {
emptyList()
}
}
otherDistances.addAll(getNestedDistances(this.name, 1))
return otherDistances.minus(currentSpace)
}
companion object {
fun from(line: String): Space {
val (part1, part2) = line.split(";")
val name = part1.split(" ")[1]
val rate = part1.split("=")[1].toInt()
val connections = part2.split("valves", "valve")[1].split(",").map { it.trim() }
return Space(name, rate, connections)
}
}
}
| 0 | Kotlin | 0 | 0 | ee8806b1b4916fe0b3d576b37269c7e76712a921 | 5,360 | Advent-Of-Code-2022 | Apache License 2.0 |
src/Day05.kt | ahmadshabib | 573,197,533 | false | {"Kotlin": 13577} | fun main() {
val input = readInput("Day05")
val stacks = createStacks(numberOfStacks(line = input[0]))
input.filter { it.contains("[") }.reversed().forEach { fillStack(it, stacks) }
input
.asSequence()
.filter { it.startsWith("move") }
.map { it.replace("move ", "") }
.map { it.replace(" from ", ",") }
.map { it.replace(" to ", ",") }
.map { it.split(",") }
.map { Triple(it[0].toInt(), it[1].toInt(), it[2].toInt()) }
.forEach { moveStacks(it, stacks, Solution.SECOND) }
stacks.forEach { if (it.isNotEmpty()) print(it.last()) }
}
private fun numberOfStacks(line: String): Int {
return (line.length + 1) / 4
}
private fun createStacks(numberOfStacks: Int): MutableList<MutableList<String>> {
val list = mutableListOf<MutableList<String>>()
for (i in 0..numberOfStacks) list.add(mutableListOf())
return list
}
private fun fillStack(line: String, stacks: MutableList<MutableList<String>>) {
stacks.forEachIndexed { index, strings ->
run {
val line2 = line.toCharArray()
if (line2.size > 1 + (index * 4)) {
val char = line2[1 + (index * 4)]
if (char.isLetter()) {
strings.add(char.toString())
}
}
}
}
}
private fun moveStacks(
order: Triple<Int, Int, Int>,
stacks: MutableList<MutableList<String>>,
solution: Solution = Solution.FIRST
) {
var elementsToMove = stacks[order.second - 1].takeLast(order.first)
when (solution) {
Solution.FIRST -> elementsToMove = elementsToMove.reversed()
else -> {}
}
stacks[order.third - 1].addAll(elementsToMove)
stacks[order.second - 1] = stacks[order.second - 1].dropLast(order.first).toMutableList()
}
enum class Solution {
FIRST, SECOND
} | 0 | Kotlin | 0 | 0 | 81db1b287ca3f6cae95dde41919bfa539ac3adb5 | 1,862 | advent-of-code-kotlin-22 | Apache License 2.0 |
src/Day22.kt | bananer | 434,885,332 | false | {"Kotlin": 36979} | data class Point3d(val x: Int, val y: Int, val z: Int)
data class Cuboid(val p1: Point3d, val p2: Point3d) {
val points: Sequence<Point3d> get() = generateSequence (p1) {
if (it.x < p2.x) {
Point3d(it.x + 1, it.y, it.z)
}
else if(it.y < p2.y) {
Point3d(p1.x, it.y + 1, it.z)
}
else if(it.z < p2.z) {
Point3d(p1.x, p1.y, it.z + 1)
}
else {
null
}
}
}
data class RebootStep(val on: Boolean, val cuboid: Cuboid)
val inputRegex = Regex("(on|off) x=(-?\\d+)\\.\\.(-?\\d+),y=(-?\\d+)\\.\\.(-?\\d+),z=(-?\\d+)\\.\\.(-?\\d+)")
fun main() {
fun parseInput(input: List<String>): List<RebootStep> = input
.map { line ->
val v = inputRegex.matchEntire(line)!!.groupValues.drop(1)
RebootStep(
v[0] == "on",
Cuboid(
Point3d(v[1].toInt(), v[3].toInt(), v[5].toInt()),
Point3d(v[2].toInt(), v[4].toInt(), v[6].toInt()),
)
)
}
fun relevantForPart1(c: Cuboid): Boolean =
c.p1.x.coerceAtMost(c.p2.x) >= -50 &&
c.p1.y.coerceAtMost(c.p2.y) >= -50 &&
c.p1.z.coerceAtMost(c.p2.z) >= -50 &&
c.p1.x.coerceAtLeast(c.p2.x) <= 50 &&
c.p1.y.coerceAtLeast(c.p2.y) <= 50 &&
c.p1.z.coerceAtLeast(c.p2.z) <= 50
fun part1(input: List<String>): Int {
val region = mutableSetOf<Point3d>()
parseInput(input).filter { relevantForPart1(it.cuboid) }
.forEach {
if (it.on) {
region.addAll(it.cuboid.points)
}
else {
region.removeAll(it.cuboid.points)
}
}
return region.size
}
fun part2(input: List<String>): Long {
return input.size.toLong()
}
// test if implementation meets criteria from the description, like:
val testInput1 = readInput("Day22_test1")
val testInput2 = readInput("Day22_test2")
val testOutput1 = part1(testInput1)
println("test output1: $testOutput1")
check(testOutput1 == 590784)
val testOutput2 = part2(testInput2)
println("test output2: $testOutput2")
//check(testOutput2 == 2758514936282235L)
val input = readInput("Day22")
println("output part1: ${part1(input)}")
println("output part2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 98f7d6b3dd9eefebef5fa3179ca331fef5ed975b | 2,444 | advent-of-code-2021 | Apache License 2.0 |
src/Day09.kt | FuKe | 433,722,611 | false | {"Kotlin": 19825} | fun main() {
val puzzleInput: List<List<Int>> = parseInput(readInput("Day09.txt"))
val aResult: Int = aSolver(puzzleInput)
println("Part one result: $aResult")
// val bResult: Int = bSolver(puzzleInput)
// println("Part two result: $bResult")
}
private fun aSolver(puzzleInput: List<List<Int>>): Int {
val lowPoints: MutableList<Int> = mutableListOf()
puzzleInput.forEachIndexed { rowIndex, list ->
list.forEachIndexed { heightIndex, height ->
val above: Int = if (rowIndex > 0) {
puzzleInput[rowIndex - 1][heightIndex]
} else { Int.MAX_VALUE }
val left: Int = if (heightIndex > 0) {
puzzleInput[rowIndex][heightIndex - 1]
} else { Int.MAX_VALUE }
val below: Int = if (rowIndex < puzzleInput.size - 1) {
puzzleInput[rowIndex + 1][heightIndex]
} else { Int.MAX_VALUE }
val right: Int = if (heightIndex < list.size -1 ) {
puzzleInput[rowIndex][heightIndex + 1]
} else { Int.MAX_VALUE }
if (height < above && height < left && height < below && height < right) {
lowPoints += height
}
}
}
return lowPoints.sumOf { it + 1 }
}
private fun bSolver(puzzleInput: List<List<Int>>): Int {
TODO()
}
private fun parseInput(input: List<String>): List<List<Int>> {
return input.map { line ->
line.map { it.toString().toInt() }
}
}
private fun test() {
val exampleInput = listOf(
"2199943210",
"3987894921",
"9856789892",
"8767896789",
"9899965678"
)
val puzzleInput: List<List<Int>> = parseInput(exampleInput)
val aResult: Int = aSolver(puzzleInput)
check(aResult == 15)
}
| 0 | Kotlin | 0 | 0 | 1cfe66aedd83ea7df8a2bc26c453df257f349b0e | 1,801 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/aoc2023/day19/day19Solver.kt | Advent-of-Code-Netcompany-Unions | 726,531,711 | false | {"Kotlin": 94973} | package aoc2023.day19
import lib.*
suspend fun main() {
setupChallenge().solveChallenge()
}
fun setupChallenge(): Challenge<Pair<Map<String, Workflow>, List<Part>>> {
return setup {
day(19)
year(2023)
//input("example.txt")
parser {
val inputGroups = it.getStringsGroupedByEmptyLine()
inputGroups.first().map { it.toWorkflow() }.associateBy { it.key } to inputGroups.last().map { it.toPart() }
}
partOne {
workflows = it.first
val accepted = it.second.filter { workflows["in"]!!.run(it) }
accepted.sumOf { it.x + it.m + it.a + it.s }.toString()
}
partTwo {
workflows = it.first
val accepted = workflows["in"]!!.run(PartRange(1..4000, 1..4000, 1..4000, 1..4000))
accepted.sumOf { it.size() }.toString()
//135056247928947 too high
}
}
}
var workflows: Map<String, Workflow> = mapOf()
data class Part(val x: Long, val m: Long, val a: Long, val s: Long)
fun String.toPart(): Part {
val values = this.replace("{", "").replace("}", "").split(",")
val x = values[0].replace("x=", "").toLong()
val m = values[1].replace("m=", "").toLong()
val a = values[2].replace("a=", "").toLong()
val s = values[3].replace("s=", "").toLong()
return Part(x, m, a, s)
}
data class Workflow(val key: String, val criteria: List<Criteria>, val default: String) {
fun run(part: Part): Boolean {
this.criteria.forEach {
val res = it.run(part)
if (res != null) {
return res.tryAccept(part)
}
}
return this.default.getResult().tryAccept(part)
}
fun run(parts: PartRange): List<PartRange> {
val res = mutableListOf<PartRange>()
var remaining = listOf(parts)
this.criteria.forEach {criteria ->
val newRemaining = mutableListOf<PartRange>()
remaining.forEach {
val eval = criteria.run(it)
res.addAll(eval.first)
newRemaining.add(eval.second)
}
remaining = newRemaining
}
if(remaining.isNotEmpty()) {
remaining.forEach {
res.addAll(default.getResult().tryAccept(it))
}
}
return res
}
}
fun String.toWorkflow(): Workflow {
val groups = this.replace("}", "").split("{")
val workflowStrings = groups.last().split(",")
val defaultRes = workflowStrings.last()
return Workflow(groups.first(), workflowStrings.dropLast(1).map { it.getCriteria() }, defaultRes)
}
interface WorkflowResult {
fun tryAccept(part: Part): Boolean
fun tryAccept(parts: PartRange): List<PartRange>
}
data class StaticResult(val isAccepted: Boolean) : WorkflowResult {
override fun tryAccept(part: Part): Boolean {
return isAccepted
}
override fun tryAccept(parts: PartRange): List<PartRange> {
return if (isAccepted) listOf(parts) else listOf()
}
}
class ComputedResult(val key: String) : WorkflowResult {
override fun tryAccept(part: Part): Boolean {
return workflows[key]!!.run(part)
}
override fun tryAccept(parts: PartRange): List<PartRange> {
return workflows[key]!!.run(parts)
}
}
data class Criteria(val category: Char, val number: Int, val acceptsGreaterThan: Boolean, val whenAccept: String) {
fun run(part: Part): WorkflowResult? {
val partValue = when (category) {
'x' -> part.x
'm' -> part.m
'a' -> part.a
's' -> part.s
else -> throw Exception("Unknown category from criteria $this")
}
val isPassed = if (acceptsGreaterThan) partValue > number else partValue < number
return if (isPassed) whenAccept.getResult() else null
}
fun run(parts: PartRange): Pair<List<PartRange>, PartRange> {
if (parts.isEmpty()) {
return (listOf<PartRange>() to parts)
}
val splitNumber = if (acceptsGreaterThan) number + 1 else number
val ranges = when (category) {
'x' -> parts.copy(x = parts.x.stopAt(splitNumber - 1)) to parts.copy(x = parts.x.startAt(splitNumber))
'm' -> parts.copy(m = parts.m.stopAt(splitNumber - 1)) to parts.copy(m = parts.m.startAt(splitNumber))
'a' -> parts.copy(a = parts.a.stopAt(splitNumber - 1)) to parts.copy(a = parts.a.startAt(splitNumber))
's' -> parts.copy(s = parts.s.stopAt(splitNumber - 1)) to parts.copy(s = parts.s.startAt(splitNumber))
else -> throw Exception("Unknown category from criteria $this")
}
return if(acceptsGreaterThan) {
whenAccept.getResult().tryAccept(ranges.second) to ranges.first
} else {
whenAccept.getResult().tryAccept(ranges.first) to ranges.second
}
}
}
fun String.getCriteria(): Criteria {
val split = this.split(":")
val number = split.first().drop(2).toInt()
val isGreater = split.first()[1] == '>'
return Criteria(this.first(), number, isGreater, split.last())
}
fun String.getResult(): WorkflowResult {
return if (this.length == 1) StaticResult(this == "A")
else ComputedResult(this)
}
data class PartRange(val x: IntRange, val m: IntRange, val a: IntRange, val s: IntRange) {
fun isEmpty(): Boolean {
return listOf(x, m, a, s).all { it.isEmpty() }
}
fun size(): Long {
return x.size().toLong() * m.size() * a.size() * s.size()
}
} | 0 | Kotlin | 0 | 0 | a77584ee012d5b1b0d28501ae42d7b10d28bf070 | 5,562 | AoC-2023-DDJ | MIT License |
src/main/kotlin/days/Day11.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package days
import util.DayInput
import util.GridCell
import util.Matrix
import java.util.*
class Day11 : Day("11") {
override fun partOne(dayInput: DayInput): Any {
return calculateDustanceSum(dayInput, 2)
}
fun distance(star1: GridCell<Char>, star2: GridCell<Char>): Int {
return Math.abs(star1.cell.column - star2.cell.column) + Math.abs(star1.cell.row - star2.cell.row)
}
override fun partTwo(dayInput: DayInput): Any {
return calculateDustanceSum(dayInput, 1000000)
}
private fun calculateDustanceSum(dayInput: DayInput, emptyRowDistance: Int): Long {
val inputList = LinkedList(dayInput.inputList().map { LinkedList(it.toList()) }.toList())
val matrix = Matrix.fromList(inputList)
val emptyRows = matrix.rows().mapIndexed { index, list ->
index to list.all { it.value == '.' }
}.filter { it.second }.map { it.first }
val emptyColumns = matrix.columns().mapIndexed { index, list ->
index to list.all { it.value == '.' }
}.filter { it.second }.map { it.first }
val stars = matrix.filter { it.value == '#' }
val starsToCompare =
stars.flatMapIndexed { index, value -> stars.subList(index + 1, stars.size).map { value to it } }
return starsToCompare.map {
val emptyRow = emptyRows.filter { row ->
row < Math.max(it.first.cell.row, it.second.cell.row) &&
row > Math.min(it.first.cell.row, it.second.cell.row)
}.count()
val emptyColumn = emptyColumns.filter { row ->
row < Math.max(it.first.cell.column, it.second.cell.column) &&
row > Math.min(it.first.cell.column, it.second.cell.column)
}.count()
(emptyRowDistance - 1).toLong() * emptyColumn.toLong() + (emptyRowDistance - 1).toLong() * emptyRow.toLong() + distance(
it.first,
it.second
).toLong()
}.sum()
}
}
fun main() {
Day11().run()
}
| 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 2,069 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/adventofcode/year2021/Day04GiantSquid.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2021
import adventofcode.Puzzle
import adventofcode.PuzzleInput
class Day04GiantSquid(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val numbers by lazy { input.lines().first().split(",").map(String::toInt) }
private val boards by lazy {
input
.split("\n\n")
.drop(1)
.map { board -> board.lines().map { row -> row.split(" ").filter(String::isNotBlank).map { Number(it.toInt()) } } }
.map(::Board)
}
private fun playBingo() =
generateSequence(0 to boards.map { board -> board.markNumber(numbers.first()) }) { (previousIndex, previousBoards) ->
previousIndex + 1 to previousBoards.map { board -> board.markNumber(numbers[previousIndex + 1]) }
}
.take(numbers.size)
override fun partOne(): Int {
val firstWinner = playBingo().first { (_, boards) -> boards.any { board -> board.hasWon() } }
val lastDrawnNumber = numbers[firstWinner.first]
val winnerBoard = firstWinner.second.first { board -> board.hasWon() }
return lastDrawnNumber * winnerBoard.sumOfAllUnmarkedNumbers()
}
override fun partTwo(): Int {
val beforeLastWinner = playBingo().last { (_, boards) -> boards.any { board -> !board.hasWon() } }
val lastDrawnNumber = numbers[beforeLastWinner.first + 1]
val winnerBoard = beforeLastWinner.second.first { board -> !board.hasWon() }.markNumber(lastDrawnNumber)
return lastDrawnNumber * winnerBoard.sumOfAllUnmarkedNumbers()
}
companion object {
private data class Number(
val value: Int,
val marked: Boolean = false
)
private data class Board(
val numbers: List<List<Number>>
) {
fun markNumber(number: Int) =
copy(numbers = numbers.map { row -> row.map { if (it.value == number) Number(it.value, true) else it } })
fun hasWon() = when {
(numbers.any { row -> row.all { it.marked } }) -> true
(numbers.first().indices.any { col -> numbers.all { row -> row[col].marked } }) -> true
else -> false
}
fun sumOfAllUnmarkedNumbers() = numbers.flatten().filterNot { it.marked }.sumOf { it.value }
}
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 2,346 | AdventOfCode | MIT License |
src/main/kotlin/year2022/Day05.kt | simpor | 572,200,851 | false | {"Kotlin": 80923} | import AoCUtils.test
fun main() {
data class Crane(val move: Int, val from: Int, val to: Int)
fun part1(input: String, debug: Boolean = false): String {
val crates = input.lines().filter { it.startsWith(" 1 ") }
.map { it.replace(" ", "") }
.last()
.toCharArray()
.map { mutableListOf<String>() }
.toMutableList()
input.lines().filter { it.contains("[") }
.map { line ->
line.chunked(4)
.map { it.trim().replace("]", "").replace("[", "") }
.mapIndexed { index, s ->
if (s.isNotBlank()) crates[index].add(0, s)
}
}
val craneMovements = input.lines().filter { it.contains("move") }
.map { line ->
val a = line.split("move|from|to".toRegex()).map { it.trim() }
Crane(a[1].toInt(), a[2].toInt(), a[3].toInt())
}
craneMovements.forEach { movement ->
for (crate in 1..movement.move) {
crates[movement.to - 1].add(crates[movement.from - 1].removeLast())
}
}
return crates.joinToString("") { it.last() }
}
fun part2(input: String, debug: Boolean = false): String {
val crates = input.lines().filter { it.startsWith(" 1 ") }
.map { it.replace(" ", "") }
.last()
.toCharArray()
.map { mutableListOf<String>() }
.toMutableList()
input.lines().filter { it.contains("[") }
.map { line ->
line.chunked(4)
.map { it.trim().replace("]", "").replace("[", "") }
.mapIndexed { index, s ->
if (s.isNotBlank()) crates[index].add(0, s)
}
}
val craneMovements = input.lines().filter { it.contains("move") }.map { line ->
val a = line.split("move|from|to".toRegex()).map { it.trim() }
Crane(a[1].toInt(), a[2].toInt(), a[3].toInt())
}
craneMovements.forEach { movement ->
val list = mutableListOf<String>()
for (crate in 1..movement.move) {
list.add(0, crates[movement.from - 1].removeLast())
}
crates[movement.to - 1].addAll(list)
}
return crates.joinToString("") { it.last() }
}
val testInput =
" [D] \n" +
"[N] [C] \n" +
"[Z] [M] [P]\n" +
" 1 2 3 \n" +
"\n" +
"move 1 from 2 to 1\n" +
"move 3 from 1 to 3\n" +
"move 2 from 2 to 1\n" +
"move 1 from 1 to 2\n"
val input = AoCUtils.readText("year2022/day05.txt")
part1(testInput, false) test Pair("CMZ", "test 1 part 1")
part1(input, false) test Pair("SHQWSRBDL", "part 1")
part2(testInput, false) test Pair("MCD", "test 2 part 2")
part2(input) test Pair("CDTQZHBRS", "part 2")
}
| 0 | Kotlin | 0 | 0 | 631cbd22ca7bdfc8a5218c306402c19efd65330b | 3,073 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/de/dikodam/calendar/Day07.kt | dikodam | 573,126,346 | false | {"Kotlin": 26584} | package de.dikodam.calendar
import de.dikodam.AbstractDay
import de.dikodam.executeTasks
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
Day07().executeTasks()
}
class Day07 : AbstractDay() {
private val terminalHistory = readInputLines().map { Day07TerminalLine.parseLine(it) }
// private val terminalHistory = """${'$'} cd /
//${'$'} ls
//dir a
//14848514 b.txt
//8504156 c.dat
//dir d
//${'$'} cd a
//${'$'} ls
//dir e
//29116 f
//2557 g
//62596 h.lst
//${'$'} cd e
//${'$'} ls
//584 i
//${'$'} cd ..
//${'$'} cd ..
//${'$'} cd d
//${'$'} ls
//4060174 j
//8033020 d.log
//5626152 d.ext
//7214296 k""".lines().map { Day07TerminalLine.parseLine(it) }
override fun task1(): String {
val dirs: Map<String, List<Day07TerminalLine>> = buildTree(terminalHistory)
val dingens = dirs.asIterable()
.sortedBy { (_, list) -> list.size }
val buffer = mutableMapOf<String, Int>()
for ((key, list) in dingens) {
buffer[key] = dirs.computeSizeOf(key)
}
return buffer.values
.filter { it <= 100_000 }
.sum()
.toString()
}
override fun task2(): String {
return ""
}
val dirSizes = mutableMapOf<String, Int>()
private fun Map<String, List<Day07TerminalLine>>.computeSizeOf(key: String): Int {
return if (dirSizes[key] != null) {
dirSizes[key]!!
} else {
val children = this[key]!!
val size = children.sumOf {
when (it) {
is DirectoryDescriptor -> this.computeSizeOf(it.name)
is FileDescriptor -> it.size
else -> error("impossible")
}
}
dirSizes[key] = size
size
}
}
private fun buildTree(lines: List<Day07TerminalLine>): Map<String, List<Day07TerminalLine>> {
var currentDir = ""
val memory: MutableMap<String, MutableList<Day07TerminalLine>> = mutableMapOf()
val queue = ArrayDeque(lines)
while (queue.isNotEmpty()) {
when (val currentLine = queue.removeFirst()) {
is CdCommand -> currentDir = currentLine.goal
LsCommand -> {
val treeElements = queue.removeWhile { it is DirectoryDescriptor || it is FileDescriptor }
.toMutableList()
memory.merge(currentDir, treeElements) { l1, l2 -> l1.addAll(l2); l1 }
}
else -> error("unexpected command")
}
}
return memory
}
}
private fun MutableMap<String, MutableList<Day07TerminalLine>>.extractChildrenFor(key: String): List<NavTreeElement> {
val mem = this
val children = mem[key]!!.map {
when (it) {
is FileDescriptor -> it.toFile()
is DirectoryDescriptor -> Dir(key, extractChildrenFor(it.name))
else -> error("this really shouldn't happen")
}
}
return children
}
sealed class NavTreeElement {
abstract val name: String
abstract fun size(): Int
}
data class Dir(override val name: String, val children: List<NavTreeElement>) : NavTreeElement() {
override fun size(): Int = children.sumOf { it.size() }
}
data class File(override val name: String, val size: Int) : NavTreeElement() {
override fun size(): Int = this.size
}
sealed class Day07TerminalLine {
companion object {
fun parseLine(line: String): Day07TerminalLine =
when {
line.startsWith("$ cd") -> CdCommand.parseLine(line)
line.startsWith("$ ls") -> LsCommand
line.startsWith("dir") -> DirectoryDescriptor.parseLine(line)
else -> FileDescriptor.parseLine(line)
}
}
}
data class CdCommand(val goal: String) : Day07TerminalLine() {
companion object {
fun parseLine(line: String): Day07TerminalLine {
// $ cd /
val (_, _, goal) = line.split(" ")
return CdCommand(goal)
}
}
}
object LsCommand : Day07TerminalLine()
data class DirectoryDescriptor(val name: String) : Day07TerminalLine() {
companion object {
fun parseLine(line: String): Day07TerminalLine {
// dir d
val (_, dirName) = line.split(" ")
return DirectoryDescriptor(dirName)
}
}
}
data class FileDescriptor(val name: String, val size: Int) : Day07TerminalLine() {
companion object {
fun parseLine(line: String): Day07TerminalLine {
// 123 a.txt
val (fileSize, fileName) = line.split(" ")
return FileDescriptor(fileName, fileSize.toInt())
}
}
}
fun FileDescriptor.toFile() = File(name, size)
fun <T> ArrayDeque<T>.remove(i: Int) = (0 until i).map { this.removeFirst() }
fun <T> ArrayDeque<T>.removeWhile(predicate: (T) -> Boolean): List<T> {
val acc = mutableListOf<T>()
while (if (firstOrNull() == null) false else predicate(first())) {
acc += removeFirst()
}
return acc
}
| 0 | Kotlin | 0 | 1 | 3eb9fc6f1b125565d6d999ebd0e0b1043539d192 | 5,111 | aoc2022 | MIT License |
y2022/src/main/kotlin/adventofcode/y2022/Day13.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
object Day13 : AdventSolution(2022, 13, "Distress Signal") {
override fun solvePartOne(input: String) = parse(input)
.chunked(2)
.withIndex()
.filter { (_, v) -> v[0] < v[1] }
.sumOf { it.index + 1 }
override fun solvePartTwo(input: String): Int {
val dividers = listOf("[[2]]", "[[6]]")
return (dividers + input).joinToString("\n")
.let(::parse)
.sorted()
.withIndex()
.filter { it.value.toString() in dividers }
.map { it.index + 1 }
.reduce(Int::times)
}
}
private fun parse(input: String): Sequence<Node> = input.lineSequence()
.filter(String::isNotEmpty)
.map(::tokenize)
.map(::parseToNode)
private fun tokenize(input: String) = iterator {
var remainder = input
while (remainder.isNotEmpty()) {
when (remainder[0]) {
'[' -> yield("[").also { remainder = remainder.drop(1) }
']' -> yield("]").also { remainder = remainder.drop(1) }
',' -> remainder = remainder.drop(1)
else -> {
val s = remainder.takeWhile { it.isDigit() }
remainder = remainder.drop(s.length)
yield(s)
}
}
}
}
private fun parseToNode(tokens: Iterator<String>): Node {
val nodes = mutableListOf<Node>()
while (tokens.hasNext()) {
when (val t = tokens.next()) {
"[" -> nodes += parseToNode(tokens)
"]" -> return Branch(nodes)
else -> nodes += Leaf(t.toInt())
}
}
return nodes.single()
}
private sealed class Node : Comparable<Node>
private data class Leaf(val i: Int) : Node() {
override fun compareTo(other: Node): Int = when (other) {
is Leaf -> i.compareTo(other.i)
is Branch -> Branch(listOf(this)).compareTo(other)
}
override fun toString() = i.toString()
}
private data class Branch(val children: List<Node>) : Node() {
override fun compareTo(other: Node): Int = when (other) {
is Leaf -> compareTo(Branch(mutableListOf(other)))
is Branch -> children.zip(other.children, Node::compareTo)
.find { it != 0 } ?: children.size.compareTo(other.children.size)
}
override fun toString() = children.joinToString(",", "[", "]")
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,391 | advent-of-code | MIT License |
src/main/kotlin/pl/klemba/aoc/day3/Main.kt | aklemba | 726,935,468 | false | {"Kotlin": 16373} | package pl.klemba.aoc.day3
import java.io.File
fun main() {
// ----- PART 1 -----
File(inputPath)
.readLines()
.let { schematic ->
schematic.mapIndexed { lineIndex, line ->
numberRegex.findAll(line)
.filter { schematic.checkIfAdjacentToASymbol(it.range, lineIndex) }
.map { it.value.toInt() }
.sum()
}.sum()
.let { println(it) }
}
// ----- PART 2 -----
val schematic = File(inputPath)
.readLines()
val numbersSchematic = schematic.mapIndexed { lineIndex, line ->
numberRegex.findAll(line)
.filter { schematic.checkIfAdjacentToASymbol(it.range, lineIndex) }
.toList()
}
schematic.mapIndexed { lineIndex, line ->
gearRegex.findAll(line)
.map {
numbersSchematic.sumGearRatio(it.range, lineIndex)
}
.sum()
}.sum()
.let { println(it) }
}
private fun List<List<MatchResult>>.sumGearRatio(range: IntRange, lineIndex: Int): Int {
val listOfAdjacentNumbers = mutableListOf<MatchResult>()
if (lineIndex != 0) {
listOfAdjacentNumbers.addAll(this[lineIndex - 1].getNumbersForIndex(range, this[0].lastIndex))
}
if (lineIndex != this.lastIndex) {
listOfAdjacentNumbers.addAll(this[lineIndex + 1].getNumbersForIndex(range, this[0].lastIndex))
}
listOfAdjacentNumbers.addAll(this[lineIndex].getNumbersForIndex(range, this[0].lastIndex))
return if (listOfAdjacentNumbers.size == 2) {
listOfAdjacentNumbers.map { it.value.toInt() }.reduce { acc, value -> acc * value }
}
else 0
}
private fun List<MatchResult>.getNumbersForIndex(range: IntRange, lastIndex: Int): List<MatchResult> {
val rangeToCheck = getRangeToCheck(range, lastIndex)
return this.filter { it.isAdjacentToGear(rangeToCheck) }
}
private fun MatchResult.isAdjacentToGear(rangeToCheck: IntRange) = range.intersect(rangeToCheck).isNotEmpty()
private fun List<String>.checkIfAdjacentToASymbol(numberIndices: IntRange, lineIndex: Int): Boolean {
// check top and bottom
if (lineIndex != 0) {
if (this[lineIndex - 1].checkIfSymbolsExistForRange(numberIndices, this[0].lastIndex)) return true
}
if (lineIndex != this.lastIndex) {
if (this[lineIndex + 1].checkIfSymbolsExistForRange(numberIndices, this[0].lastIndex)) return true
}
// check sides
if (numberIndices.first != 0) {
if (this[lineIndex][numberIndices.first - 1].isASymbol()) return true
}
if (numberIndices.last != this[lineIndex].lastIndex) {
if (this[lineIndex][numberIndices.last + 1].isASymbol()) return true
}
return false
}
private fun String.checkIfSymbolsExistForRange(indexRange: IntRange, lineLastIndex: Int): Boolean {
val rangeToCheck: IntRange = getRangeToCheck(indexRange, lineLastIndex)
return substring(rangeToCheck).any { it.isASymbol() }
}
private fun getRangeToCheck(indexRange: IntRange, lineLastIndex: Int): IntRange {
val rangeToCheck: IntRange = when {
indexRange.first == 0 -> IntRange(0, indexRange.last + 1)
indexRange.last == lineLastIndex -> IntRange(indexRange.first - 1, indexRange.last)
else -> IntRange(indexRange.first - 1, indexRange.last + 1)
}
return rangeToCheck
}
private fun Char.isASymbol() = this.isDigit().not() && this != '.'
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day3/input.txt"
private val numberRegex = Regex("\\d+")
private val gearRegex = Regex("\\*") | 0 | Kotlin | 0 | 1 | 2432d300d2203ff91c41ffffe266e19a50cca944 | 3,479 | adventOfCode2023 | Apache License 2.0 |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D16.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2020
import io.github.pshegger.aoc.common.BaseSolver
class Y2020D16 : BaseSolver() {
override val year = 2020
override val day = 16
override fun part1(): Int = parseInput().let { input ->
input.nearby.mapNotNull { it.invalidField(input.validators) }.sum()
}
override fun part2(): Long = parseInput().withoutInvalidNearby().let { input ->
val possibleIndices = input.validators.associateWith { validator ->
input.own.fields.indices.filter { fieldI ->
input.nearby.all { ticket -> validator.isFieldValid(ticket.fields[fieldI]) }
}
}
val (solvedInput, _) = input.validators.fold(Pair(input, emptyList<Int>())) { (input, alreadyFound), _ ->
val single = possibleIndices.entries.first { (_, v) -> (v - alreadyFound).size == 1 }.key
val possibility = ((possibleIndices[single] ?: error("WTF?!")) - alreadyFound)[0]
Pair(input.copyWithValidatorFieldIndex(single, possibility), alreadyFound + possibility)
}
solvedInput.validators
.filter { it.name.startsWith("departure") }
.fold(1L) { acc, validator ->
acc * solvedInput.own.fields[validator.fieldIndex]
}
}
private fun parseInput() =
readInput {
readLines().fold(Pair(0, Input.empty)) { (mode, input), line ->
if (line.isBlank()) {
Pair(mode + 1, input)
} else {
when (mode) {
0 -> Pair(mode, input.copy(validators = input.validators + Validator.parseString(line)))
2 -> Pair(mode, input.copy(own = Ticket.parseString(line)))
4 -> Pair(mode, input.copy(nearby = input.nearby + Ticket.parseString(line)))
1, 3 -> Pair(mode + 1, input)
else -> Pair(mode, input)
}
}
}.second
}
private data class Input(val validators: List<Validator>, val own: Ticket, val nearby: List<Ticket>) {
fun copyWithValidatorFieldIndex(validator: Validator, fieldIndex: Int) = copy(
validators = validators.filterNot { it == validator } + validator.copy(fieldIndex = fieldIndex)
)
fun withoutInvalidNearby() = copy(
nearby = nearby.filter { it.invalidField(validators) == null }
)
companion object {
val empty = Input(emptyList(), Ticket(emptyList()), emptyList())
}
}
private data class Validator(val name: String, val ranges: List<IntRange>, val fieldIndex: Int = -1) {
fun isFieldValid(field: Int) = ranges.any { field in it }
companion object {
fun parseString(str: String) = validatorRegex.matchEntire(str)?.let { res ->
Validator(
res.groupValues[1],
listOf(
IntRange(res.groupValues[2].toInt(), res.groupValues[3].toInt()),
IntRange(res.groupValues[4].toInt(), res.groupValues[5].toInt()),
)
)
} ?: error("Invalid validator line")
private val validatorRegex = "(.+): (\\d+)-(\\d+) or (\\d+)-(\\d+)".toRegex()
}
}
private data class Ticket(val fields: List<Int>) {
fun invalidField(validators: List<Validator>) =
fields.firstOrNull { field -> validators.none { it.isFieldValid(field) } }
companion object {
fun parseString(str: String) = Ticket(str.trim().split(",").map { it.toInt() })
}
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 3,693 | advent-of-code | MIT License |
src/AoC9.kt | Pi143 | 317,631,443 | false | null | import java.io.File
fun main() {
println("Starting Day 9 A Test 1")
calculateDay9PartA("Input/2020_Day9_A_Test1", 5)
println("Starting Day 9 A Real")
calculateDay9PartA("Input/2020_Day9_A", 25)
println("Starting Day 9 B Test 1")
calculateDay9PartB("Input/2020_Day9_A_Test1", 5)
println("Starting Day 9 B Real")
calculateDay9PartB("Input/2020_Day9_A", 25)
}
fun calculateDay9PartA(file: String, preambleLength: Int): Long {
val Day9Data = readDay9Data(file)
for (i in preambleLength until Day9Data.size) {
if (!checkNumberValid(Day9Data.subList(i - preambleLength, i), Day9Data[i])) {
println(Day9Data[i])
return Day9Data[i]
}
}
return -1
}
fun calculateDay9PartB(file: String, preambleLength: Int): Long {
val Day9Data = readDay9Data(file)
var invalidNumber: Long = -1
for (i in preambleLength until Day9Data.size) {
if (!checkNumberValid(Day9Data.subList(i - preambleLength, i), Day9Data[i])) {
invalidNumber = Day9Data[i]
break
}
}
for (i in 0 until Day9Data.size) {
var j = i + 1
while (j < Day9Data.size && Day9Data.subList(i, j).sum() < invalidNumber) {
j++
}
if (Day9Data.subList(i, j).sum() == invalidNumber) {
val max = Day9Data.subList(i, j).max()
val min = Day9Data.subList(i, j).min()
println("start is ${Day9Data[i]} at index $i and end is ${Day9Data[j - 1]} at index ${j - 1}")
println("max is $max and min is $min")
println(max!! + min!!)
return min + max
}
}
return -1
}
fun checkNumberValid(numberList: MutableList<Long>, targetNum: Long): Boolean {
val sorted = numberList.sorted()
var lowIndex = 0
var highIndex = sorted.size - 1
while (sorted[lowIndex] + sorted[highIndex] != targetNum && highIndex > lowIndex) {
if (sorted[lowIndex] + sorted[highIndex] < targetNum) {
lowIndex++
}
if (sorted[lowIndex] + sorted[highIndex] > targetNum) {
highIndex--
}
}
return lowIndex < highIndex
}
fun readDay9Data(input: String): MutableList<Long> {
val xmasList: MutableList<Long> = ArrayList()
File(localdir + input).forEachLine { xmasList.add(it.toLong()) }
return xmasList
}
| 0 | Kotlin | 0 | 1 | fa21b7f0bd284319e60f964a48a60e1611ccd2c3 | 2,383 | AdventOfCode2020 | MIT License |
day07/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | import com.google.common.graph.GraphBuilder
import com.google.common.graph.MutableGraph
import java.io.File
import java.util.*
fun main() {
println("Part I: the solution is ${solvePartI(makeGraph(readInputFile(), true))}.")
println("Part II: the solution is ${solvePartII(makeGraph(readInputFile(), false))}.")
}
fun readInputFile(): List<String> {
return File(ClassLoader.getSystemResource("input.txt").file).readLines()
}
fun solvePartI(graph: MutableGraph<Chain>): String {
var result = ""
while (graph.nodes().size > 0) {
val sortedAvailableChains = getAvailableChains(graph).sortedBy { it.name }
result += sortedAvailableChains[0].name
graph.removeNode(sortedAvailableChains[0])
}
return result
}
fun solvePartII(graph: MutableGraph<Chain>): Int {
var result = 0
val workerCurrentChain = (0 until Constants.PART_II_TOTAL_WORKERS)
.associate { it -> Pair(it, null) }
.toMutableMap<Int, Chain?>()
while (getTotalSizeOfGraph(graph) > 0) {
val sortedAvailableChainsNotStarted = getAvailableChains(graph).sortedBy { it.name }
val queueOfAvailableChainsNotStarted = ArrayDeque<Chain>(sortedAvailableChainsNotStarted)
for (worker in 0 until Constants.PART_II_TOTAL_WORKERS) {
var chainToUpdate: Chain? = null
// assign chain to worker, if available
// if worker has already started chain they must finish
// otherwise look for an available chain that hasn't been started
if (workerCurrentChain[worker] != null) {
chainToUpdate = workerCurrentChain[worker]!!
} else if (queueOfAvailableChainsNotStarted.isNotEmpty()) {
chainToUpdate = queueOfAvailableChainsNotStarted.first
workerCurrentChain[worker] = chainToUpdate
queueOfAvailableChainsNotStarted.remove()
}
if (chainToUpdate != null) {
chainToUpdate.removeNode()
// if chain empty after removing node, delete chain
if (chainToUpdate.getSize() == 0) {
graph.removeNode(chainToUpdate)
workerCurrentChain[worker] = null
}
}
// since workers work simultaneously, only count time for one worker
if (worker == 0) {
result++
}
}
}
return result
}
fun makeGraph(input: List<String>, isPartI: Boolean): MutableGraph<Chain> {
val result = GraphBuilder.directed().allowsSelfLoops(false).build<Chain>()
input.forEach { line ->
val leftChainName = line[5]
val rightChainName = line[36]
val leftChainSize: Int
val rightChainSize: Int
if (isPartI) {
leftChainSize = 1
rightChainSize = 1
} else {
// 'A' -> 61 seconds, 'B' -> 62 seconds, 'C' -> 63 seconds, etc
leftChainSize = leftChainName.toInt() - 4
rightChainSize = rightChainName.toInt() - 4
}
val leftChain = Chain(leftChainName, leftChainSize)
val rightChain = Chain(rightChainName, rightChainSize)
result.putEdge(leftChain, rightChain)
}
return result
}
fun getTotalSizeOfGraph(graph: MutableGraph<Chain>): Int {
return graph.nodes()
.sumBy { chain -> chain.getSize() }
}
fun getAvailableChains(graph: MutableGraph<Chain>): List<Chain> {
return graph.nodes()
.filter { chain -> graph.inDegree(chain) == 0 && !chain.started }
.map { chain -> chain }
}
data class Node(val name: String)
data class Chain(val name: Char, val initialSize: Int) {
private val graph = GraphBuilder.directed().allowsSelfLoops(false).build<Node>()
var started: Boolean = false
init {
var leftNode = Node("$name$initialSize")
graph.addNode(leftNode)
for (i in 1..(initialSize - 1)) {
val rightNode = Node("$name${initialSize - i}")
graph.putEdge(leftNode, rightNode)
leftNode = rightNode
}
}
fun getSize(): Int {
return graph.nodes().size
}
fun removeNode() {
val leftNode = Node("$name${getSize()}")
graph.removeNode(leftNode)
started = true
}
}
object Constants {
const val PART_II_TOTAL_WORKERS = 5
}
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 4,395 | AdventOfCode2018 | MIT License |
src/day9/puzzle09.kt | brendencapps | 572,821,792 | false | {"Kotlin": 70597} | package day9
import Puzzle
import PuzzleInput
import java.io.File
import kotlin.math.abs
fun day9Puzzle() {
Day9PuzzleSolution().solve(Day9PuzzleInput("inputs/day9/example.txt", 2, 13))
Day9PuzzleSolution().solve(Day9PuzzleInput("inputs/day9/input.txt", 2, 6271))
Day9PuzzleSolution().solve(Day9PuzzleInput("inputs/day9/example.txt", 10, 1))
Day9PuzzleSolution().solve(Day9PuzzleInput("inputs/day9/example2.txt", 10, 36))
Day9PuzzleSolution().solve(Day9PuzzleInput("inputs/day9/input.txt", 10, 2458))
}
class Day9PuzzleInput(val input: String, numKnots: Int, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) {
val moves = File(input).readLines()
val pointsVisited = HashMap<Pair<Int, Int>, Boolean>()
private val knots = Array(numKnots) {
Pair(0, 0)
}
private fun getKnot(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
val x = head.first - tail.first
val y = head.second - tail.second
if(abs(x) > 1 || abs(y) > 1) {
return Pair(tail.first + x.coerceIn(-1, 1), tail.second + y.coerceIn(-1, 1))
}
return tail
}
private fun moveHead(newHead: Pair<Int, Int>) {
knots[0] = newHead
for(i in 1 until knots.size) {
knots[i] = getKnot(knots[i-1], knots[i])
}
pointsVisited[knots.last()] = true
}
fun moveHead(xOffset: Int, yOffset: Int, amount: Int) {
for(move in 1 .. amount) {
moveHead(Pair(knots[0].first + xOffset, knots[0].second + yOffset))
}
}
}
class Day9PuzzleSolution : Puzzle<Int, Day9PuzzleInput>() {
override fun solution(input: Day9PuzzleInput): Int {
input.pointsVisited[Pair(0, 0)] = true
input.moves.forEach { move ->
val moveParts = move.split(" ")
val direction = moveParts[0]
val amount = moveParts[1].toInt()
when(direction) {
"U" -> input.moveHead(0, 1, amount)
"D" -> input.moveHead(0, -1, amount)
"L" -> input.moveHead(-1, 0, amount)
"R" -> input.moveHead(1, 0, amount)
}
}
return input.pointsVisited.size
}
} | 0 | Kotlin | 0 | 0 | 00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3 | 2,283 | aoc_2022 | Apache License 2.0 |
src/main/kotlin/days/Solution08.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import adventOfCode.util.TripleOf
import kotlin.math.sqrt
typealias TurnOrder = CharArray
typealias NodeMap = Map<String, PairOf<String>>
typealias CycleNumber = Long
object Solution08 : Solution<Pair<TurnOrder, NodeMap>>(AOC_YEAR, 8) {
private val Long.primeFactors
get(): Map<Long, Int> {
fun MutableMap<Long, Int>.add(n: Long) = this.merge(n, 1, Int::plus)
val factors = mutableMapOf<Long, Int>()
var n = this
while (n % 2 == 0L) {
factors.add(2)
n /= 2
}
val squareRoot = sqrt(n.toDouble()).toLong()
for (d in 3..squareRoot step 2) {
while (n % d == 0L) {
factors.add(d)
n /= d
}
}
if (n > 2) {
factors.add(n)
}
return factors
}
private infix fun Long.`^`(n: Int) = (1..n).map { n }.fold(1, Long::times)
private fun Long.modularInverse(m: Long): Long {
val modThis = this % m
return (1..<modThis).firstOrNull { (modThis * it) % m == 1L } ?: 0
}
private fun gcd(x: Long, y: Long): Long {
var a = x
var b = y
while (b > 0) {
val temp = b
b = a % b
a = temp
}
return a
}
private fun lcm(x: Long, y: Long): Long {
return x * (y / gcd(x, y))
}
private fun chineseRemainderTheorem(congruences: List<PairOf<CycleNumber>>): CycleNumber? {
// Decompose moduli into prime powers
val expandedCongruences = mutableMapOf<CycleNumber, List<Pair<Int, CycleNumber>>>()
congruences.forEach { (m, r) ->
m.primeFactors.forEach { (p, power) ->
expandedCongruences.merge(p, listOf(power to (r `^` power)), List<Pair<Int, CycleNumber>>::plus)
}
}
// Check for any conflicting congruences
val baseCongruences = mutableMapOf<CycleNumber, Set<CycleNumber>>()
val maxPrimePower = mutableMapOf<CycleNumber, Int>().withDefault { 0 }
val maxPrimeRemainder = mutableMapOf<CycleNumber, CycleNumber>()
expandedCongruences.forEach { (p, candidates) ->
candidates.forEach { (power, r) ->
baseCongruences.merge(p, setOf(r % p), Set<Long>::union)
if (power > maxPrimePower.getValue(p)) {
maxPrimePower[p] = power
maxPrimeRemainder[p] = r
}
}
}
if (baseCongruences.values.any { it.size > 1 }) return null
// Apply coprime case of CRT
val coprimeCongruences = maxPrimePower.entries.associate { (p, power) -> p `^` power to maxPrimeRemainder.getValue(p) }
val product = coprimeCongruences.keys.reduce(Long::times)
return coprimeCongruences.entries.sumOf { (m, r) ->
val M = product / m
val N = M.modularInverse(m)
r * M * N
}
}
private fun findCycleCongruence(turnOrder: TurnOrder, nodeMap: NodeMap, startNode: String): TripleOf<CycleNumber> {
var currNode = startNode
val seen = mutableMapOf<Pair<String, Int>, CycleNumber>()
var step = 0L
while (true) {
val turnIndex = (step % turnOrder.size).toInt()
val turn = turnOrder[turnIndex]
val nextNodes = nodeMap.getValue(currNode)
currNode = if (turn == 'L') nextNodes.first else nextNodes.second
step++
val key = currNode to turnIndex
val firstSeen = seen[key]
if (firstSeen == null) {
seen[key] = step
continue
}
seen.entries.firstOrNull { it.key.first.endsWith('Z') }
?.let {
return Triple(firstSeen, step - firstSeen, it.value - firstSeen)
}
}
}
override fun getInput(handler: InputHandler): Pair<TurnOrder, NodeMap> {
val (turns, nodes) = handler.getInput("\n\n")
val nodeMap = nodes.split('\n')
.map { it.split(" = ") }
.associate { pieces ->
val source = pieces.first()
val dests = pieces.last().trim('(', ')').split(", ")
source to (dests.first() to dests.last())
}
return turns.toCharArray() to nodeMap
}
override fun solve(input: Pair<TurnOrder, NodeMap>): PairOf<CycleNumber?> {
val (turnOrder, nodeMap) = input
var ans1: CycleNumber? = null
val congruences = mutableListOf<PairOf<CycleNumber>>()
nodeMap.keys.filter { it.endsWith('A') }
.forEach {
val (start, length, offset) = findCycleCongruence(turnOrder, nodeMap, it)
congruences.add(length to start + offset)
if (it == "AAA") ans1 = start + offset
}
val combinedCycle = congruences.map(PairOf<CycleNumber>::first).reduce(::lcm)
var crt = chineseRemainderTheorem(congruences)
if (crt != null) {
crt %= combinedCycle
if (crt <= 0) crt += combinedCycle
}
return ans1 to crt
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 5,344 | Advent-of-Code-2023 | MIT License |
src/Day08.kt | fasfsfgs | 573,562,215 | false | {"Kotlin": 52546} | fun main() {
fun part1(forest: Forest): Int {
var visibleTrees = 0
for (row in 0..forest.rows.lastIndex)
for (column in 0..forest.rows[0].lastIndex)
if (forest.isTreeVisible(row, column)) visibleTrees++
return visibleTrees
}
fun part2(forest: Forest): Int {
var highestScenicScore = 0
for (row in 0..forest.rows.lastIndex)
for (column in 0..forest.rows[0].lastIndex)
highestScenicScore = maxOf(highestScenicScore, forest.getScenicScore(row, column))
return highestScenicScore
}
val testForest = readInput("Day08_test").toForest()
check(part1(testForest) == 21)
check(testForest.getScenicScore(1, 2) == 4)
check(part2(testForest) == 8)
val forest = readInput("Day08").toForest()
println(part1(forest))
println(part2(forest))
}
fun List<String>.toForest() = Forest(map { line -> line.map { it.toString().toInt() } })
data class Forest(val rows: List<List<Int>>) {
fun isTreeVisible(row: Int, column: Int): Boolean {
if (row == 0 || column == 0 || row == rows.lastIndex || column == rows[0].lastIndex) return true
return isVisibleFromLeft(row, column)
|| isVisibleFromRight(row, column)
|| isVisibleFromTop(row, column)
|| isVisibleFromBottom(row, column)
}
private fun isVisibleFromLeft(row: Int, column: Int) =
(0 until column).all { rows[row][it] < rows[row][column] }
private fun isVisibleFromRight(row: Int, column: Int) =
(rows[0].lastIndex downTo column + 1).all { rows[row][it] < rows[row][column] }
private fun isVisibleFromTop(row: Int, column: Int) =
(0 until row).all { rows[it][column] < rows[row][column] }
private fun isVisibleFromBottom(row: Int, column: Int) =
(rows.lastIndex downTo row + 1).all { rows[it][column] < rows[row][column] }
fun getScenicScore(row: Int, column: Int): Int {
if (row == 0 || column == 0 || row == rows.lastIndex || column == rows[0].lastIndex) return 0
val left = getScenicScoreFromLeft(row, column)
val right = getScenicScoreFromRight(row, column)
val top = getScenicScoreFromTop(row, column)
val bottom = getScenicScoreFromBottom(row, column)
return left * right * top * bottom
}
private fun getScenicScoreFromLeft(row: Int, column: Int): Int =
getScenicScore(row, column, column - 1 downTo 0) { rows[row][it] }
private fun getScenicScoreFromRight(row: Int, column: Int): Int =
getScenicScore(row, column, column + 1..rows[0].lastIndex) { rows[row][it] }
private fun getScenicScoreFromTop(row: Int, column: Int): Int =
getScenicScore(row, column, row - 1 downTo 0) { rows[it][column] }
private fun getScenicScoreFromBottom(row: Int, column: Int): Int =
getScenicScore(row, column, row + 1..rows.lastIndex) { rows[it][column] }
private fun getScenicScore(row: Int, column: Int, range: IntProgression, treeToCheck: (Int) -> Int): Int {
var visibleTrees = 0
for (i in range) {
visibleTrees++
if (treeToCheck(i) >= rows[row][column]) break
}
return visibleTrees
}
}
| 0 | Kotlin | 0 | 0 | 17cfd7ff4c1c48295021213e5a53cf09607b7144 | 3,263 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2022/Day08.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2022
fun main() {
fun part1(input: Array<IntArray>): Int {
val verticalEdgesCount = input.size * 2
val betweenHorizontalEdgesCount = (input.first().size - 2) * 2
var visibleTreesCount = verticalEdgesCount + betweenHorizontalEdgesCount
for (rowIndex in 1 until input.lastIndex) {
for (colIndex in 1 until input.first().lastIndex) {
val currTree = input[rowIndex][colIndex]
when {
//left
input[rowIndex].take(colIndex).all { currTree > it } -> visibleTreesCount++
//right
input[rowIndex].drop(colIndex + 1).all { currTree > it } -> visibleTreesCount++
//top
input.take(rowIndex).all { currTree > it[colIndex] } -> visibleTreesCount++
//bottom
input.drop(rowIndex + 1).all { currTree > it[colIndex] } -> visibleTreesCount++
}
}
}
return visibleTreesCount
}
fun part2(input: Array<IntArray>): Int {
var viewingDistanceScore = 0
for (rowIndex in 1 until input.lastIndex) {
for (colIndex in 1 until input.first().lastIndex) {
val currTree = input[rowIndex][colIndex]
val right = input[rowIndex].drop(colIndex + 1).takeWhileInclusive { currTree > it }.size
val left = input[rowIndex].take(colIndex).asReversed().takeWhileInclusive { currTree > it }.size
val bottom = input.drop(rowIndex + 1).takeWhileInclusive { currTree > it[colIndex] }.size
val top = input.take(rowIndex).asReversed().takeWhileInclusive { currTree > it[colIndex] }.size
viewingDistanceScore = maxOf(viewingDistanceScore, (top * left * right * bottom))
}
}
return viewingDistanceScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAs2DIntArray("Day08_test")
check(part1(testInput).also(::println) == 21)
check(part2(testInput).also(::println) == 8)
val input = readInputAs2DIntArray("Day08")
println(part1(input))
println(part2(input))
}
private fun <T> List<T>.takeWhileInclusive(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
list.add(item)
if (!predicate(item))
break
}
return list
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 2,481 | Kotlin-AOC-2023 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day17/Day17.kt | pfmaggi | 438,378,048 | false | {"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pietromaggi.aoc2021.day17
import com.pietromaggi.aoc2021.readInput
import kotlin.math.absoluteValue
data class Point(val x: Int, val y: Int)
data class Area(val topLeft: Point, val bottomRight: Point)
data class Velocities(val x: Int, val y: Int)
fun part1(input: Area) = (1 until input.bottomRight.y.absoluteValue).sum()
fun check(start: Velocities, target: Area) : Pair<Boolean, Int> {
var position = Point(0, 0)
var currentVelocities = start
var result = false
var max = 0
while (!result && (position.x < target.bottomRight.x) && (position.y > target.bottomRight.y)) {
max = position.y.coerceAtLeast(max)
position = Point(position.x + currentVelocities.x, position.y + currentVelocities.y)
currentVelocities = Velocities((currentVelocities.x - 1).coerceAtLeast(0), (currentVelocities.y - 1))
result = ((target.topLeft.x <= position.x) && (position.x <= target.bottomRight.x) &&
((target.bottomRight.y <= position.y) && (position.y <= target.topLeft.y)))
}
return Pair(result, max)
}
fun part2(input: Area): List<Int> {
val results = mutableListOf<Int>()
for (xRange in 0..input.bottomRight.x) {
for (yRange in input.bottomRight.y..(-input.bottomRight.y)) {
val(inTarget, max) = check(Velocities(xRange, yRange), input)
if (inTarget) {
results.add(max)
}
}
}
return results
}
fun parseArea(input: List<String>) : Area {
val (x, y) = input[0].removePrefix("target area: ").split(", ")
val (x1, x2) = x.removePrefix("x=").split("..").map(String::toInt)
val (y2, y1) = y.removePrefix("y=").split("..").map(String::toInt)
return Area(Point(x1, y1), Point(x2, y2))
}
fun main() {
val input = readInput("Day17")
val area = parseArea(input)
println(part1(area))
// println(part2(area).maxOrNull())
println(part2(area).count())
}
| 0 | Kotlin | 0 | 0 | 7c4946b6a161fb08a02e10e99055a7168a3a795e | 2,539 | AdventOfCode | Apache License 2.0 |
src/Day01.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} |
val nameToDigit = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9",
)
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val digits = it.filter { char -> char.isDigit() }
"${digits.first()}${digits.last()}".toInt()
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val first = "${nameToDigit.keys.joinToString(separator = "|")}|\\d".toRegex().find(it)
?.let { match -> if (match.value.any { char -> char.isDigit() }) match.value else nameToDigit[match.value]!! }!!
val last =
"${nameToDigit.keys.joinToString(separator = "|", transform = { key -> key.reversed() })}|\\d".toRegex()
.find(it.reversed())
?.let { match -> if (match.value.any { char -> char.isDigit() }) match.value else nameToDigit[match.value.reversed()]!! }!!
(first + last).toInt()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
// println(part1(testInput))
println(part2(testInput))
//check(part1(testInput) == 142)
check(part2(testInput) == 281)
val input = readInput("Day01")
//println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 1,443 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | fun main() {
val strategy = readInput("Day02")
.map (::parseLine)
fun part1(strategy: List<Pair<Int, Int>>): Int {
// let x, y denotes Rock/Paper/Scissor of opponent and you
// the result will be
// you win IFF y - x ≡ 1 (mod 3)
// draw IFF y - x ≡ 1 (mod 3)
// you lost IFF y - x ≡ -1 (mod 3)
return strategy.sumOf { (opponent, player) ->
val playScore = player + 1
val outcomeScore = when ((player - opponent).mod(3)) {
1 -> 6
0 -> 3
else -> 0
}
playScore + outcomeScore
}
}
fun part2(strategy: List<Pair<Int, Int>>): Int {
return strategy.sumOf { (opponent, outcome) ->
val playScore = (opponent + outcome - 1).mod(3) + 1
val outcomeScore = outcome * 3
playScore + outcomeScore
}
}
val testStrategy = readInput("Day02_test")
.map (::parseLine)
check(part1(testStrategy) == 15)
check(part2(testStrategy) == 12)
println("Part 1")
println(part1(strategy))
println("Part 2")
println(part2(strategy))
}
fun parseLine(line: String): Pair<Int, Int> = line[0] - 'A' to line[2] - 'X'
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 1,260 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day05.kt | Kaaveh | 572,838,356 | false | {"Kotlin": 13188} | private fun parse(input: List<String>): Pair<Int, MutableList<MutableList<Char>>> {
val rawMap = mutableListOf<String>()
var mapIndex = 0
do {
rawMap.add(input[mapIndex])
mapIndex++
} while ("[" in input[mapIndex])
val rowCount = input[mapIndex].trim().split("\\s+".toRegex()).size
val movementIndex = mapIndex + 2
val stations = MutableList<MutableList<Char>>(rowCount) { mutableListOf() }
rawMap.forEach { row ->
val elements = row.chunked(4).map { it.trim() }
elements.forEachIndexed { index, element ->
if (element.isNotEmpty()) {
val new = element.replace("[", "").replace("]", "")[0]
stations[index].add(new)
}
}
}
return Pair(movementIndex, stations)
}
private fun String.toMovement(): Triple<Int, Int, Int> {
val movement = this
.replace("move ", "")
.replace(" from ", ",")
.replace(" to ", ",")
.trim()
val (number, source, destination) = movement.split(",").map { it.toInt() }
return Triple(number, source, destination)
}
private fun part1(input: List<String>): String {
val (movementIndex, stations) = parse(input)
for (i in movementIndex until input.size) {
val (number, source, destination) = input[i].toMovement()
repeat(number) {
stations[destination - 1].add(0, stations[source - 1].removeFirst())
}
}
return stations.map { it.first() }.joinToString("")
}
private fun part2(input: List<String>): String {
val (movementIndex, stations) = parse(input)
for (i in movementIndex until input.size) {
val (number, source, destination) = input[i].toMovement()
stations[source - 1]
.subList(0, number)
.reversed()
.forEach {
stations[destination - 1].add(0, it)
stations[source - 1].removeFirst()
}
}
return stations.map { it.first() }.joinToString("")
}
fun main() {
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 9022f1a275e9c058655898b64c196f7a0a494b48 | 2,242 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day16.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2022
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
import at.mpichler.aoc.lib.ShortestPaths
open class Part16A : PartSolution() {
private lateinit var valves: Map<String, Valve>
protected var maxFlow: Int = 0
protected lateinit var closedValves: Set<String>
override fun parseInput(text: String) {
val valves = mutableMapOf<String, Valve>()
val connectionNames = mutableMapOf<String, List<String>>()
val pattern = Regex("Valve (.*?) has flow rate=(\\d+); tunnels? leads? to valves? (.*)")
for (line in text.trim().split("\n")) {
val result = pattern.find(line)!!
val connections = result.groupValues[3].split(", ")
val name = result.groupValues[1]
connectionNames[name] = connections
valves[name] = Valve(name, result.groupValues[2].toInt())
}
for ((name, con) in connectionNames) {
val connections = mutableListOf<Valve>()
for (connection in con) {
connections.add(valves[connection]!!)
}
valves[name]?.connections = connections
}
this.valves = valves
}
override fun config() {
maxFlow = valves.values.sumOf { it.flow }
closedValves = valves.filter { it.value.flow > 0 }.map { it.key }.toSet()
}
override fun compute(): Int {
val traversal = ShortestPaths { node, _ -> nextEdges(node) }
traversal.startFrom(Node("AA", closedValves, 0))
for ((_, closed, _) in traversal) {
if (traversal.depth == 30 || closed.isEmpty()) {
return maxFlow * 30 - traversal.distance
}
}
error("Non reachable")
}
protected fun nextEdges(node: Node): Sequence<Pair<Node, Int>> {
val (pos, closed, flow) = node
val valve = valves[pos]!!
return sequence {
val cost = maxFlow - flow
if (pos in closed) {
yield(Pair(Node(pos, closed.minus(pos), flow + valve.flow), cost))
}
for (v in valve.connections) {
yield(Pair(Node(v.name, closed, flow), cost))
}
}
}
override fun getExampleAnswer(): Int {
return 1651
}
protected data class Node(val name: String, val closed: Set<String>, val flow: Int)
data class Valve(val name: String, val flow: Int) {
var connections: List<Valve> = listOf()
}
}
class Part16B : Part16A() {
override fun compute(): Int {
val traversal = ShortestPaths(this::nextEdgesB)
traversal.startFrom(NodeB("AA", "AA", closedValves, 0))
for ((_, closed, _) in traversal) {
if (traversal.depth == 26 || closed.isEmpty()) {
return maxFlow * 26 - traversal.distance
}
}
error("Non reachable")
}
private fun nextEdgesB(node: NodeB, traversal: ShortestPaths<NodeB>): Sequence<Pair<NodeB, Int>> {
val (pos1, pos2, closed, flow) = node
return sequence {
nextEdges(Node(pos1, closed, flow)).forEach { (s1, weight1) -> nextEdges(Node(pos2, closed, flow)).forEach { (s2, _) ->
if (s1 != s2 || s1.closed == closed) {
yield(Pair(NodeB(s1.name, s2.name, s1.closed.intersect(s2.closed), s1.flow + s2.flow - flow), weight1))
}
} }
}
}
override fun getExampleAnswer(): Int {
return 1707
}
private data class NodeB(val pos1: String, val pos2: String, val closed: Set<String>, val flow: Int)
}
fun main() {
Day(2022, 16, Part16A(), Part16B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 3,706 | advent-of-code-kotlin | MIT License |
src/Day05.kt | fdorssers | 575,986,737 | false | null | data class Step(val move: Int, val from: Int, val to: Int)
fun main() {
fun parseLines(lines: List<String>): Pair<MutableMap<Int, String>, List<Step>> {
val dock = lines
.takeWhile { line -> !line.startsWith(" 1") }
.map { line ->
(1..line.length)
.step(4)
.withIndex()
.map { (num, ind) -> Pair(num + 1, line[ind]) }
.filter { it.second != ' ' }
}
.reversed()
.flatten()
.groupBy({ it.first }, { it.second })
.mapValues { tmp -> tmp.value.joinToString("") }
.toMutableMap()
val steps = lines
.filter { it.startsWith("move") }
.map { line -> line.split("\\s".toRegex()) }
.map { Step(move = it[1].toInt(), from = it[3].toInt(), to = it[5].toInt()) }
return Pair(dock, steps)
}
fun part(dock: MutableMap<Int, String>, steps: List<Step>, reverse: Boolean): String {
steps.forEach { step ->
dock[step.to] = dock[step.to] + (dock[step.from]
?.takeLast(step.move)
?.let { str -> if (reverse) str.reversed() else str })
dock[step.from] = dock[step.from]?.dropLast(step.move) ?: ""
}
return dock
.entries
.sortedBy { it.key }
.map { it.value.last() }
.joinToString("")
}
val (exampleDock, exampleSteps) = parseLines(readInputLines("Day05_test"))
val (dock, steps) = parseLines(readInputLines("Day05"))
check(part(exampleDock.toMutableMap(), exampleSteps, reverse = true) == "CMZ")
println("Solution for part 1: ${part(dock.toMutableMap(), steps, reverse = true)}")
check(part(exampleDock.toMutableMap(), exampleSteps, reverse = false) == "MCD")
println("Solution for part 2: ${part(dock.toMutableMap(), steps, reverse = false)}")
} | 0 | Kotlin | 0 | 0 | bdd1300b8fd6a1b8bce38aa6851e68d05193c636 | 1,953 | advent-of-code-kotlin | Apache License 2.0 |
y2020/src/main/kotlin/adventofcode/y2020/Day17.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2020
import adventofcode.io.AdventSolution
fun main() = Day17.solve()
object Day17 : AdventSolution(2020, 17, "Conway Cubes")
{
override fun solvePartOne(input: String): Int
{
val active = parse(input).map { it + 0 }.toSet()
return generateSequence(ConwayCube(active), ConwayCube::next).take(7).last().activeCells.size
}
override fun solvePartTwo(input: String): Int
{
val active = parse(input).map { it + 0 + 0 }.toSet()
return generateSequence(ConwayCube(active), ConwayCube::next).take(7).last().activeCells.size
}
private fun parse(input:String): List<Coordinate> = buildList {
input.lines().forEachIndexed { y, line ->
line.forEachIndexed { x, ch ->
if (ch == '#')
add(listOf(x, y))
}
}
}
private data class ConwayCube(val activeCells: Set<Coordinate>)
{
fun next(): ConwayCube = interior().filter(::aliveInNext).toSet().let(::ConwayCube)
private fun aliveInNext(c: Coordinate): Boolean = countActiveNeighbors(c) in if (c in activeCells) 3..4 else 3..3
private fun countActiveNeighbors(c: Coordinate): Int = neighbors
.map { c.zip(it, Int::plus) }
.count { it in activeCells }
private val neighbors: List<Coordinate> by lazy { expand(activeCells.first().map { -1..1 }) }
private fun interior(): List<Coordinate>
{
val min = activeCells.reduce { a, b -> a.zip(b, ::minOf) }.map { it - 1 }
val max = activeCells.reduce { a, b -> a.zip(b, ::maxOf) }.map { it + 1 }
return expand(min.zip(max, Int::rangeTo))
}
}
}
private fun expand(ranges: List<IntRange>): List<Coordinate> =
ranges.fold(listOf(emptyList())) { acc, r ->
acc.flatMap { l -> r.map(l::plus) }
}
private typealias Coordinate = List<Int> | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,921 | advent-of-code | MIT License |
solutions/aockt/y2022/Y2022D02.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2022
import aockt.y2022.Y2022D02.RpsChoice.*
import aockt.y2022.Y2022D02.RpsChoice.Companion.versus
import io.github.jadarma.aockt.core.Solution
object Y2022D02 : Solution {
private enum class RpsChoice(val score: Int) {
Rock(1),
Paper(2),
Scissors(3);
val winsAgainst: RpsChoice get() = winTable[this]!!
val losesAgainst: RpsChoice get() = loseTable[this]!!
companion object {
/** Lookup table that determines which choice beats which other. */
val winTable = mapOf(Rock to Scissors, Paper to Rock, Scissors to Paper)
/** Lookup table that determines which choice loses to which other. */
val loseTable = mapOf(Rock to Paper, Paper to Scissors, Scissors to Rock)
/**
* Compares two choices from the perspective of the first and returns the round score.
* Returns 3 for draw, 6 for player win, and 0 for [other] win.
*/
infix fun RpsChoice.versus(other: RpsChoice): Int = when (other) {
this -> 3
winsAgainst -> 6
else -> 0
}
}
}
@JvmInline
private value class RpsStrategy(
private val strategy: List<Pair<RpsChoice, RpsChoice>>,
) : List<Pair<RpsChoice, RpsChoice>> by strategy {
/** Play a game of Rock-Paper-Scissors and return the final score. */
fun simulateGame(): Int = strategy.sumOf { (opponent, player) -> player.score + (player versus opponent) }
companion object {
private val inputRegex = Regex("""^([ABC]) ([XYZ])$""")
/** Converts a character to an [RpsChoice]. */
private fun Char.toRpsChoice() = when (this) {
'A' -> Rock
'B' -> Paper
'C' -> Scissors
else -> throw IllegalArgumentException("Character '$this' is not a valid encoding for RPS.")
}
/** Converts a character to an [RpsChoice] depending on the [opponent] move. */
private fun Char.toOutcomeChoice(opponent: RpsChoice): RpsChoice = when (this) {
'X' -> opponent.winsAgainst
'Y' -> opponent
'Z' -> opponent.losesAgainst
else -> throw IllegalArgumentException("Character '$this' is not a valid encoding for RPS.")
}
/** Returns the [RpsStrategy] described by the [input], throwing [IllegalArgumentException] if invalid. */
fun parse(input: String, partTwo: Boolean = false): RpsStrategy =
input
.lines()
.map {
val match = inputRegex.matchEntire(it)
requireNotNull(match) { "Line '$it' is not a valid strategy." }
val opponent = match.groupValues[1].first().toRpsChoice()
val player = match.groupValues[2].first().let { p ->
if (partTwo) p.toOutcomeChoice(opponent)
else (p - ('X' - 'A')).toRpsChoice()
}
opponent to player
}
.let(::RpsStrategy)
}
}
override fun partOne(input: String) = RpsStrategy.parse(input, partTwo = false).simulateGame()
override fun partTwo(input: String) = RpsStrategy.parse(input, partTwo = true).simulateGame()
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,477 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/com/chriswk/aoc/advent2018/Day12.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2018
object Day12 {
fun part1(input: List<String>): Int {
val (pots, rules) = parseInput(input)
return (1..20).fold(pots) { state, _ ->
step(state, rules)
}.fold(0) { sumSoFar, pot -> if (pot.hasPlant) sumSoFar + pot.idx else sumSoFar }
}
fun part2(input: List<String>): Long {
val (pots, rules) = parseInput(input)
var generation = 0
var previous = pots
var current = previous
do {
previous = current
current = step(previous, rules)
generation++
} while (previous.map { it.hasPlant } != current.map { it.hasPlant } )
val changes = current.first().idx - previous.first().idx
val generationsLeft = 5e10.toLong() - generation
val change = generationsLeft * changes
return current.fold(0L) { totalSum, pot ->
if (pot.hasPlant) { pot.idx + change + totalSum }
else totalSum
}
}
fun parseInput(input: List<String>): Pair<List<Pot>, List<Rule>> {
val pots = input.first().substringAfter("initial state: ").mapIndexed { i, c -> Pot(i, c == '#')}
val rules = input.drop(2).map { r ->
val neighbourList = r.take(5).map { it == '#' }
val result = r.last() == '#'
Rule(neighbourList, result)
}
return pots to rules
}
fun step(currentPods: List<Pot>, rules: List<Rule>): List<Pot> {
val newGeneration = expandGeneration(currentPods).windowed(5, 1).map { looking ->
val actual = looking.map { it.hasPlant }
val hasPlant = rules.firstOrNull { it.mask == actual }?.result ?: false
Pot(looking[2].idx, hasPlant)
}
return newGeneration.compress()
}
fun List<Pot>.compress(): List<Pot> {
return this.dropWhile { !it.hasPlant }.dropLastWhile { !it.hasPlant }
}
fun expandGeneration(currentGeneration: List<Pot>): List<Pot> {
val currentStart = currentGeneration.first().idx
val currentEnd = currentGeneration.last().idx
return (currentStart - 5 until currentStart).map { Pot(it) } + currentGeneration + (currentEnd+1..currentEnd+5).map { Pot(it) }
}
data class Pot(val idx: Int, val hasPlant: Boolean = false)
data class Rule(val mask: List<Boolean>, val result: Boolean)
} | 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,393 | adventofcode | MIT License |
src/Day07.kt | frungl | 573,598,286 | false | {"Kotlin": 86423} | data class Node(var weight: Int, val go: MutableMap<String, Int>, val par: Int)
fun main() {
fun parseToTree(input: List<String>): MutableList<Node> {
val graph = mutableListOf(Node(0, emptyMap<String, Int>().toMutableMap(), -1))
var pos = 0
input.drop(1).forEach { cmd ->
if (cmd.startsWith("$")) {
if(cmd.contains("cd")) {
val to = cmd.takeLastWhile { it != ' ' }
pos = if (to == "..") {
graph[pos].par
} else {
graph[pos].go[to]!!
}
}
} else {
if(cmd.contains("dir")) {
val to = cmd.takeLastWhile { it != ' ' }
val ind = graph.size
graph[pos].go[to] = ind
graph.add(Node(0, emptyMap<String, Int>().toMutableMap(), pos))
} else {
graph[pos].weight += cmd.takeWhile { it != ' ' }.toInt()
}
}
}
return graph
}
fun dfs(v: Int, graph: MutableList<Node>, res: MutableList<Int>): Int {
val weight = graph[v].weight + graph[v].go.values.fold(0) { acc, next ->
acc + dfs(next, graph, res)
}
res.add(weight)
return weight
}
fun part1(input: List<String>): Int {
val graph = parseToTree(input)
val sizes = emptyList<Int>().toMutableList()
dfs(0, graph, sizes)
return sizes.filter { it <= 100000 }.sum()
}
fun part2(input: List<String>): Int {
val graph = parseToTree(input)
val sizes = emptyList<Int>().toMutableList()
dfs(0, graph, sizes)
val need = 30000000 - (70000000 - sizes.last())
return sizes.partition { it < need }.second.min()
}
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 | 0 | d4cecfd5ee13de95f143407735e00c02baac7d5c | 2,078 | aoc2022 | Apache License 2.0 |
src/main/kotlin/net/mguenther/adventofcode/day14/Day14.kt | mguenther | 115,937,032 | false | null | package net.mguenther.adventofcode.day14
import net.mguenther.adventofcode.day10.KnotHash
import java.math.BigInteger
/**
* @author <NAME> (<EMAIL>)
*/
class Day14Additive(private val prefix: String) {
val grid: List<IntArray> = IntRange(0, 127)
.map { "$prefix-$it" }
.map { KnotHash(256).checksum(it) }
.map { BigInteger(it, 16).toString(2).padStart(128, '0') }
.map { s -> s.map { it-'0' } }
.map { it.toIntArray() }
var groups = 2
fun groups(): Int {
groups = 2 // set to initial value
grid.forEachIndexed { x, row ->
row.forEachIndexed { y, col -> if (col < 2 && col > 0) {
groups++
mark(x, y)
}
}
}
return groups - 2 // minus the initial 2
}
private fun neighbours(row: Int, col: Int): List<Pair<Int, Int>> =
listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1))
.map { Pair(it.first + row, it.second + col) }
.filter { it.first in 0..127 }
.filter { it.second in 0..127 }
private fun mark(row: Int, col: Int) {
if (grid[row][col] == 1) {
grid[row][col] = groups
neighbours(row, col).forEach { mark(it.first, it.second) }
}
}
}
class Day14Reductionism(private val prefix: String) {
val grid: List<IntArray> = IntRange(0, 127)
.map { "$prefix-$it" }
.map { KnotHash(256).checksum(it) }
.map { BigInteger(it, 16).toString(2).padStart(128, '0') }
.map { s -> s.map { it-'0' } }
.map { it.toIntArray() }
var groups = 0
fun groups(): Int {
grid.forEachIndexed { x, row ->
row.forEachIndexed { y, col -> if (col == 1) {
groups++
mark(x, y)
}
}
}
return groups
}
private fun neighbours(row: Int, col: Int): List<Pair<Int, Int>> =
listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1))
.map { Pair(it.first + row, it.second + col) }
.filter { it.first in 0..127 }
.filter { it.second in 0..127 }
private fun mark(row: Int, col: Int) {
if (grid[row][col] == 1) {
grid[row][col] = 0
neighbours(row, col).forEach { mark(it.first, it.second) }
}
}
}
fun defrag(prefix: String): Int {
return IntRange(0, 127)
.map { "$prefix-$it" }
.map { KnotHash(256).checksum(it) }
.map { BigInteger(it, 16).toString(2).padStart(128, '0') }
.map { it.count { c -> c.equals('1') } }
.sum()
}
fun main(args: Array<String>) {
println(defrag("ugkiagan"))
println(Day14Additive("ugkiagan").groups())
println(Day14Reductionism("ugkiagan").groups())
} | 0 | Kotlin | 0 | 0 | c2f80c7edc81a4927b0537ca6b6a156cabb905ba | 2,950 | advent-of-code-2017 | MIT License |
src/Day08.kt | nguyendanv | 573,066,311 | false | {"Kotlin": 18026} | fun main() {
fun part1(input: List<String>): Int {
val rows = input.map { it.map(Char::digitToInt) }
val columns = rows.first().indices.map { i -> rows.map { it[i] } }
return rows.flatMapIndexed { i, row ->
row.mapIndexed { j, height ->
val isTaller: (Int) -> Boolean = { height > it }
val westVisible = row.take(j).all(isTaller)
val eastVisible = row.drop(j + 1).all(isTaller)
val northVisible = columns[j].take(i).all(isTaller)
val southVisible = columns[j].drop(i + 1).all(isTaller)
westVisible || eastVisible || northVisible || southVisible
}
}.count { it }
}
fun part2(input: List<String>): Int {
val rows = input.map { it.map(Char::digitToInt) }
val columns = rows.first().indices.map { i -> rows.map { it[i] } }
return rows.flatMapIndexed { i, row ->
row.mapIndexed { j, height ->
val isTaller: (Int) -> Boolean = { height > it }
val westScore = row.take(j).takeLastWhileInclusive(isTaller).count()
val eastScore = row.drop(j + 1).takeWhileInclusive(isTaller).count()
val northScore = columns[j].take(i).takeLastWhileInclusive(isTaller).count()
val southScore = columns[j].drop(i + 1).takeWhileInclusive(isTaller).count()
westScore * eastScore * northScore * southScore
}
}.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput)==21)
check(part2(testInput)==8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
fun <T> List<T>.takeWhileInclusive(last: Boolean = false, predicate: (T) -> Boolean): List<T> {
var shouldContinue = true
return (if (last) ::takeLastWhile else ::takeWhile) {
val result = shouldContinue
shouldContinue = predicate(it)
result
}
}
fun <T> List<T>.takeWhileInclusive(predicate: (T) -> Boolean): List<T> {
return this.takeWhileInclusive(false, predicate)
}
fun <T> List<T>.takeLastWhileInclusive(predicate: (T) -> Boolean): List<T> {
return this.takeWhileInclusive(true, predicate)
} | 0 | Kotlin | 0 | 0 | 376512583af723b4035b170db1fa890eb32f2f0f | 2,321 | advent2022 | Apache License 2.0 |
src/Day07.kt | melo0187 | 576,962,981 | false | {"Kotlin": 15984} | import Command.Companion.toCommandOrNull
import FileSystemNode.Companion.toFileSystemNodeOrNull
sealed interface FileSystemNode {
fun size(): Long
data class Dir(val name: String, val contents: MutableList<FileSystemNode> = mutableListOf()) : FileSystemNode {
override fun size(): Long =
contents.fold(0) { acc, fileSystemNode ->
val size = when (fileSystemNode) {
is Dir -> fileSystemNode.size()
is File -> fileSystemNode.size
}
acc + size
}
}
data class File(val size: Long) : FileSystemNode {
override fun size(): Long = size
}
companion object {
fun String.toFileSystemNodeOrNull(): FileSystemNode? =
when {
startsWith("dir") -> Dir(takeLastWhile { it != ' ' })
startsWith('$') -> null
else -> File(takeWhile { it != ' ' }.toLong())
}
}
}
sealed interface Command {
data class CDin(val dirName: String) : Command
object CDout : Command
object LS : Command
companion object {
fun String.toCommandOrNull(): Command? =
when {
endsWith("..") -> CDout
startsWith("$ cd") -> CDin(takeLastWhile { it != ' ' })
startsWith("$ ls") -> LS
else -> null
}
}
}
fun main() {
fun part1(input: List<String>): Long {
var currentDir = FileSystemNode.Dir("/")
return input
.fold(mutableListOf(currentDir)) { dirs, line ->
when (val command = line.toCommandOrNull()) {
Command.CDout -> {
// do nothing
}
is Command.CDin -> {
currentDir = dirs.find { it.name == command.dirName }
?: error("Dir we cd into should have been added already when it was read from ls output")
}
Command.LS -> {
// do nothing
}
null -> {
when (val node = line.toFileSystemNodeOrNull()) {
is FileSystemNode.Dir ->
currentDir.contents.add(node)
.also { dirs.add(node) }
is FileSystemNode.File ->
currentDir.contents.add(node)
null ->
error("Every line should either be a command or ls output, but was $line")
}
}
}
dirs
}
.filter { dir ->
dir.size() <= 100000
}
.sumOf(FileSystemNode.Dir::size)
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437.toLong())
val input = readInput("Day07")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 97d47b84e5a2f97304a078c3ab76bea6672691c5 | 3,220 | kotlin-aoc-2022 | Apache License 2.0 |
src/Day05.kt | paul-matthews | 433,857,586 | false | {"Kotlin": 18652} | import kotlin.math.sign
val VENT_LINE_FORMAT = """^(\d+),(\d+)\s*->\s*(\d+),(\d+)$""".toRegex()
typealias Coordinate = Pair<Int, Int>
typealias Line = Pair<Coordinate, Coordinate>
fun Line.isNotDiagonal(): Boolean = ((first.first == second.first) or (first.second == second.second))
val MatchResult.groupIntValues: List<Int>
get() = groupValues.drop(1).map { it.toInt() }
fun List<String>.toNearbyVents(allowDiagonal: Boolean = false): List<Line> =
fold(mutableListOf()) {acc, line ->
VENT_LINE_FORMAT.find(line)?.let {mr ->
if (mr.groups.size == 5) {
val currentLine = Line(Coordinate(mr.groupIntValues[0], mr.groupIntValues[1]),
Coordinate(mr.groupIntValues[2], mr.groupIntValues[3]))
if (allowDiagonal || currentLine.isNotDiagonal()) {
acc.add(currentLine)
}
}
}
acc
}
typealias OverlapMap = Array<Array<Int>>
fun OverlapMap.get(coord: Coordinate) = get(coord.second)[coord.first]
fun OverlapMap.set(coord: Coordinate, value: Int) {
get(coord.second)[coord.first] = value
}
fun OverlapMap.println() = map {
println(it.joinToString())
this
}
typealias HydrothermalMap = Pair</* Lines */ List<Line>, /* Matches */ OverlapMap>
fun List<Line>.createMap(): HydrothermalMap {
val coords = map { it.first } + map { it.second }
val maxX = coords.maxOf { it.first }
val maxY = coords.maxOf { it.second }
return HydrothermalMap(
this,
Array(maxY + 1) { Array(maxX + 1) { 0 } }
)
}
fun OverlapMap.markLine(line: Line): OverlapMap {
val markings = clone()
val start = line.first
val end = line.second
val incX = sign((end.first - start.first).toDouble()).toInt()
val incY = sign((end.second - start.second).toDouble()).toInt()
var curX = start.first
var curY = start.second
while (true) {
markings.apply {
get(curY)[curX] = get(curY)[curX] + 1
}
if (curX == end.first && curY == end.second)
break
curX += incX
curY += incY
}
return markings
}
fun HydrothermalMap.getOverlapPoints(): List<Int> {
var markings = second
first.map { markings = second.markLine(it) }
return markings.flatten()
}
fun main() {
fun part1(input: List<String>) =
input
.toNearbyVents()
.createMap()
.getOverlapPoints()
.count { it > 1 }
fun part2(input: List<String>): Int =
input
.toNearbyVents(true)
.createMap()
.getOverlapPoints()
.count { it > 1 }
val testInput = readFileContents("Day05_test")
val part1Result = part1(testInput)
check(part1Result == 5) { "Expected: 5 but found $part1Result" }
val part2Result = part2(testInput)
check((part2Result) == 12) { "Expected 12 but is: $part2Result" }
val input = readFileContents("Day05")
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 2f90856b9b03294bc279db81c00b4801cce08e0e | 3,047 | advent-of-code-kotlin-template | Apache License 2.0 |
src/Day02.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | fun main() {
fun part1(input: List<String>): Int {
val scores = mapOf("X" to 1, "Y" to 2, "Z" to 3)
val outcomes = mapOf(
"A X" to 3, "A Y" to 6, "A Z" to 0,
"B X" to 0, "B Y" to 3, "B Z" to 6,
"C X" to 6, "C Y" to 0, "C Z" to 3,
)
var totalScore = 0
for (line in input) {
val (_, snd) = line.split(" ")
totalScore += outcomes[line]!! + scores[snd]!!
}
return totalScore
}
fun part2(input: List<String>): Int {
val outcomes = mapOf("X" to 0, "Y" to 3, "Z" to 6)
val scores = mapOf(
"A X" to 3, "A Y" to 1, "A Z" to 2,
"B X" to 1, "B Y" to 2, "B Z" to 3,
"C X" to 2, "C Y" to 3, "C Z" to 1,
)
var totalScore = 0
for (line in input) {
val (_, desiredOutcome) = line.split(" ")
totalScore += scores[line]!! + outcomes[desiredOutcome]!!
}
return totalScore
}
// 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 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 1,283 | aoc2022 | Apache License 2.0 |
src/Day02.kt | zirman | 572,627,598 | false | {"Kotlin": 89030} | fun main() {
fun gameScore(myMove: Long, theirMove: Long): Long {
return myMove + 1 + when (myMove) {
theirMove -> 3
(theirMove + 1) % 3 -> 6
else -> 0
}
}
fun part1(input: List<String>): Long {
return input.sumOf {
val round = it.split(" ")
val them = (round[0][0] - 'A').toLong()
val me = (round[1][0] - 'X').toLong()
gameScore(me, them)
}
}
fun part2(input: List<String>): Long {
fun move(myMove: Long, theirMove: Long): Long {
return when (myMove) {
0L -> (theirMove + 2) % 3
1L -> theirMove
else -> (theirMove + 1) % 3
}
}
return input.sumOf {
val round = it.split(" ")
val them = (round[0][0] - 'A').toLong()
val me = (round[1][0] - 'X').toLong()
gameScore(move(me, them), them)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15L)
check(part2(testInput) == 12L)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 2ec1c664f6d6c6e3da2641ff5769faa368fafa0f | 1,263 | aoc2022 | Apache License 2.0 |
src/Day02.kt | Moonpepperoni | 572,940,230 | false | {"Kotlin": 6305} | fun main() {
fun String.toRPSNumerical() : Int {
return if (this == "A" || this == "X") {
0
} else if (this == "B" || this == "Y") {
1
} else {
2
}
}
fun String.toGame() : Pair<Int, Int> {
val strategy = this.split(" ")
return strategy[0].toRPSNumerical() to strategy[1].toRPSNumerical()
}
fun Pair<Int,Int>.getResult() : Int {
return (this.second + 1) + if (this.first == this.second) {
3
} else if ((this.first + 1) % 3 == this.second) {
6
} else {
0
}
}
fun part1(input: List<String>): Int {
return input
.map(String::toGame)
.sumOf { it.getResult() }
}
fun Pair<Int, Int>.getScoreFor2() : Int {
return when (this.second) {
0 -> (this.first + 2) % 3 + 1
1 -> this.first + 4
else -> (this.first + 1) % 3 + 7
}
}
fun part2(input: List<String>): Int {
return input.map(String::toGame).sumOf(Pair<Int,Int>::getScoreFor2)
}
// 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 | 946073042a985a5ad09e16609ec797c075154a21 | 1,399 | moonpepperoni-aoc-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.