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/Day04.kt | ajmfulcher | 573,611,837 | false | {"Kotlin": 24722} | fun main() {
fun parse(line: String): List<List<Int>> = line
.split(",")
.map { it.split("-").map { it.toInt() } }
fun fullyContains(pair1: List<Int>, pair2: List<Int>): Boolean {
if (pair1[0] == pair2[0] || pair1[1] == pair2[1]) return true
if (pair1[0] > pair2[0]) return fullyContains(pair2, pair1)
return pair1[1] > pair2[1]
}
fun overlaps(pair1: List<Int>, pair2: List<Int>): Boolean {
if (pair1[0] > pair2[0]) return overlaps(pair2, pair1)
return pair1[1] >= pair2[0]
}
fun part1(input: List<String>): Int {
var total = 0
input.forEach { line ->
val p = parse(line)
if (fullyContains(p[0], p[1])) total += 1
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
input.forEach { line ->
val p = parse(line)
if (overlaps(p[0], p[1])) total += 1
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
println(part1(testInput))
check(part1(testInput) == 2)
val input = readInput("Day04")
println(part1(input))
println(part2(testInput))
check(part2(testInput) == 4)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 981f6014b09e347241e64ba85e0c2c96de78ef8a | 1,325 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/solutions/Day11MonkeyInTheMiddle.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import utils.Input
import utils.Maths
import utils.Solution
// run only this day
fun main() {
Day11MonkeyInTheMiddle()
}
class Day11MonkeyInTheMiddle : Solution() {
init {
begin("Day 11 - Monkey in the Middle")
val input = Input.parseLines(filename = "/d11_monkey_decisions.txt")
.chunked(7)
.map {
Monkey(
items = it[1].substringAfter(": ").split(", ").map { n -> n.toLong() }.toMutableList(),
operation = parseOperation(it[2]),
divisor = it[3].substringAfter("by ").toInt(),
throwTo = Pair(it[4].substringAfter("monkey ").toInt(), it[5].substringAfter("monkey ").toInt())
)
}
val sol1 = calculateMonkeyBusiness(input.map { it.copy(items = it.items.toMutableList()) })
output("Level of Monkey Business", sol1)
val sol2 = calculateMonkeyBusiness(input, worryReduction = false)
output("Level of Monkey Business When Worrying More", sol2)
}
private fun calculateMonkeyBusiness(monkeys: List<Monkey>, worryReduction: Boolean = true): Long {
var round = 1
val end = if (worryReduction) 21 else 10_001
val lcm = monkeys.map { it.divisor }.reduce { acc, n ->
Maths.lcm(acc, n)
}
while (round < end) {
monkeys.forEach { m ->
// inspect all at once
m.inspections += m.items.size
while (m.items.size > 0) {
var item = m.items.removeFirst()
// operate
item = m.operation(item)
if (worryReduction)
item /= 3
else item %= lcm
// throw
monkeys[
if (m.test(item)) m.throwTo.first
else m.throwTo.second
].items.add(item)
}
}
round++
}
return monkeys.map { it.inspections }.sorted().takeLast(2).reduce { acc, n -> acc * n }
}
// parse the operation line, needed extra work because of the "old" string, blech
private fun parseOperation(s: String): (Long) -> Long {
val parts = s.substringAfter("old ")
.split(" ")
return when {
parts[0] == "*" && parts[1] != "old" -> { n -> n * parts[1].toLong() }
parts[0] == "*" && parts[1] == "old" -> { n -> n * n }
parts[0] == "+" && parts[1] != "old" -> { n -> n + parts[1].toLong() }
else -> { n -> n + n }
}
}
data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val divisor: Int,
val test: (Long) -> Boolean = { n -> n % divisor == 0L },
val throwTo: Pair<Int, Int>,
var inspections: Long = 0
)
} | 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 2,951 | advent-of-code-2022 | MIT License |
src/day13/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day13
import println
import readInput
fun main() {
class Block(block: List<String>) {
val width = block[0].length
val height = block.size
var map = block.map { it.toCharArray() }
var smudgePoint: Pair<Int, Int> = Pair(0, 0)
var withSmudgePoint = false
var OPPOSITE = mapOf('.' to '#', '#' to '.')
fun get(row: Int, column: Int): Char {
var ch = map[row][column]
if (withSmudgePoint && smudgePoint.first == row && smudgePoint.second == column) {
return OPPOSITE[ch]!!
}
return ch
}
fun checkHorizontalMirror(index: Int): Boolean {
var steps = intArrayOf(height - index, index).min();
return (1 .. steps).all {step ->
(0..<width).all { it ->
get(index - step, it) == get(index + (step - 1), it)
}
}
}
fun checkVerticalMirror(index: Int): Boolean {
var steps = intArrayOf(width - index, index).min();
return (1 .. steps).all {step ->
(0..<height).all { it ->
get(it, index - step) == get(it, index + (step - 1))
}
}
}
fun reflectionPoints(differentFrom: Int = 0): Int {
for ( i in 1..<height) {
if (checkHorizontalMirror(i) && i * 100 != differentFrom) return i * 100
}
for ( i in 1..<width) {
if (checkVerticalMirror(i) && i != differentFrom) return i
}
return 0
}
fun findSmuggedReflectionPoint(): Int {
var originalReflectionPoint = reflectionPoints()
withSmudgePoint = true
for(row in 0..<height) {
for(column in 0..<width) {
smudgePoint = Pair(row, column)
var result = reflectionPoints(originalReflectionPoint)
if (result > 0 && result != originalReflectionPoint) {
"Smudge point: ($row, $column) [$originalReflectionPoint]-> $result".println()
return result
}
}
}
"Error!!!".println()
return 0
}
}
fun originalReflectionPoint(block: List<String>): Int {
var result = Block(block).reflectionPoints()
return result
}
fun smudgeReflectionPoint(block: List<String>): Int {
var result = Block(block).findSmuggedReflectionPoint()
return result
}
fun parseBlocks(input: List<String>): List<List<String>> {
var result = mutableListOf<List<String>>()
var currentBlock = mutableListOf<String>()
input.forEach{
if(it.isEmpty()) {
result += currentBlock
currentBlock = mutableListOf()
} else {
currentBlock += it
}
}
result += currentBlock
return result
}
check(parseBlocks(readInput("day13/test1")).sumOf(::originalReflectionPoint) == 405)
"Part 1:".println()
parseBlocks(readInput("day13/input")).sumOf(::originalReflectionPoint).println()
check(parseBlocks(readInput("day13/test1")).sumOf(::smudgeReflectionPoint) == 400)
"Part 2:".println()
parseBlocks(readInput("day13/test2")).sumOf(::smudgeReflectionPoint).println()
parseBlocks(readInput("day13/input")).sumOf(::smudgeReflectionPoint).println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 3,534 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2017/Day21.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2017
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.Point
import com.nibado.projects.advent.resourceLines
object Day21 : Day {
private val input = resourceLines(2017, 21).map { it.split(" => ") }.map { Square(it[0].split("/")) to Square(it[1].split("/")) }
private val two = input.filter { it.first.square.size == 2 }.map { it.first.rotations() to it.second }
private val three = input.filter { it.first.square.size == 3 }.map { it.first.rotations() to it.second }
private val start = Square(listOf(".#.", "..#", "###"))
override fun part1() = solve(5)
override fun part2() = solve(18)
private fun solve(iterations: Int): String {
var field = Field(3)
field.write(start, Point(0, 0))
(1..iterations).forEach {
val size = if (field.size % 2 == 0) 2 else 3
val newField = Field((size + 1) * field.size / size)
for (y in 0 until field.size / size) {
for (x in 0 until field.size / size) {
val match = (if (size == 3) three else two).filter { it.first.any { field.matches(it, Point(x * size, y * size)) } }
newField.write(match.first().second, Point(x * (size + 1), y * (size + 1)))
}
}
field = newField
}
return field.count().toString()
}
data class Field(val size: Int) {
val field = (0 until size).map { "X".repeat(size).toCharArray() }
fun write(square: Square, p: Point) = square.points.forEach {
val np = p.plus(it.x, it.y)
field[np.y][np.x] = square.square[it.y][it.x]
}
fun matches(square: Square, p: Point) = square.points.none {
val np = p.plus(it.x, it.y)
field[np.y][np.x] != square.square[it.y][it.x]
}
fun count() = field.sumBy { it.count { it == '#' } }
}
data class Square(val square: List<String>) {
val points = (0 until square.size).flatMap { x -> (0 until square.size).map { y -> Point(x, y) } }
private fun flipV() = Square(square.map { it.reversed() })
private fun flipH() = if (square.size == 2) Square(listOf(square[1], square[0])) else Square(listOf(square[2], square[1], square[0]))
private fun rot90(): Square {
val chars = square.map { it.toCharArray() }
points.forEach {
val x = square.size - 1 - it.y
chars[it.x][x] = square[it.y][it.x]
}
return Square(chars.map { String(it) })
}
fun rotations(): Set<Square> {
val r90 = rot90()
val r180 = r90.rot90()
val r270 = r180.rot90()
return listOf(this, flipV(), flipH(), r90, r180, r270, r90.flipH(), r90.flipV(), r180.flipH(), r180.flipV()).toSet()
}
}
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 2,903 | adventofcode | MIT License |
src/y2021/d04/Day04.kt | AndreaHu3299 | 725,905,780 | false | {"Kotlin": 31452} | package y2021.d03
import println
import readInput
fun main() {
val classPath = "y2021/d04"
class Board {
private var board: Array<IntArray>
private var marked: Array<BooleanArray>
constructor(input: List<String>) {
val board = Array(5) { IntArray(5) }
input
.filter { it.isNotBlank() }
.forEachIndexed { y, line ->
board[y] = line.split(' ').filter { it.isNotBlank() }.map { it.toInt() }.toIntArray()
}
this.board = board
this.marked = Array(5) { BooleanArray(5) }
}
fun call(num: Int): Boolean {
board.forEachIndexed { y, rows ->
rows.forEachIndexed { x, n ->
if (n == num) {
marked[y][x] = true
return checkWin(y, x)
}
}
}
return false
}
private fun checkWin(y: Int, x: Int): Boolean {
// check horizontal
return marked[y].all { it }
// check vertical
.or(marked.map { it[x] }.all { it })
// check diagonal
// .or(
// if (y == x)
// marked[0][0] && marked[1][1] && marked[2][2] && marked[3][3] && marked[4][4]
// else if (y + x == 4)
// marked[0][4] && marked[1][3] && marked[2][2] && marked[3][1] && marked[4][0]
// else false
// )
}
fun calc(lastCalledNum: Int): Int {
var num = 0
board.forEachIndexed { y, rows ->
rows.forEachIndexed { x, n ->
num += if (!marked[y][x]) n else 0
}
}
return num * lastCalledNum
}
}
fun part1(input: List<String>): Int {
val nums = input[0].split(",").map { it.toInt() }
val boards = input.takeLast(input.size - 2).chunked(6) { Board(it) }
var result: List<Pair<Int, Boolean>>
for (i in nums) {
result = boards
.mapIndexed { index, board -> Pair(index, board.call(i)) }
.filter { it.second }
if (result.isNotEmpty()) {
return result.maxOf { boards[it.first].calc(i) }
}
}
return 0
}
fun part2(input: List<String>): Int {
val nums = input[0].split(",").map { it.toInt() }
var boards = input.takeLast(input.size - 2).chunked(6) { Board(it) }
for (i in nums) {
if (boards.size == 1 && boards[0].call(i)) {
return boards[0].calc(i)
} else {
boards = boards
.filter { !it.call(i) }
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${classPath}/test")
part1(testInput).println()
part2(testInput).println()
val input = readInput("${classPath}/input")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e | 3,153 | aoc | Apache License 2.0 |
src/day20/d20_1.kt | svorcmar | 720,683,913 | false | {"Kotlin": 49110} | fun main() {
val input = ""
val k = input.toInt() / 10
// sieve[i] == 0 iff i is prime
// == k iff k is a prime divisor of i
val sieve = sieve(k)
val memo = Array<Map<Int, Int>?>(sieve.size) { null }
for (i in 2 until sieve.size) {
val s = sigma1(i, sieve, memo)
if (s >= k) {
println(i)
break
}
}
}
fun sigma1(n: Int, sieve: Array<Int>, memo: Array<Map<Int, Int>?>): Int =
primeDivisors(n, sieve, memo).map { (k, v) -> sumPowers(k, v) }.reduce(Int::times)
fun sumPowers(n: Int, maxPow: Int): Int = (0 .. maxPow).map { Math.pow(n.toDouble(), it.toDouble()).toInt() }.sum()
fun primeDivisors(n: Int, sieve: Array<Int>, memo: Array<Map<Int, Int>?>): Map<Int, Int> {
val r = memo[n]
if (r != null)
return r
val c = if (sieve[n] == 0)
mapOf(n to 1)
else
primeDivisors(n / sieve[n], sieve, memo).toMutableMap().also { it.merge(sieve[n], 1, Int::plus) }
memo[n] = c
return c
}
fun sieve(n: Int): Array<Int> {
val arr = Array(n + 1) { 0 }
for (i in 2 .. n) {
if (arr[i] == 0) {
for (m in 2 * i .. n step i) {
arr[m] = i
}
}
}
return arr
}
| 0 | Kotlin | 0 | 0 | cb097b59295b2ec76cc0845ee6674f1683c3c91f | 1,173 | aoc2015 | MIT License |
src/Day02.kt | BenD10 | 572,786,132 | false | {"Kotlin": 6791} |
val matrix = mapOf(
Move.ROCK to mapOf(
Move.SCISSORS to Move.LOSE,
Move.ROCK to Move.DRAW,
Move.PAPER to Move.WIN,
),
Move.PAPER to mapOf(
Move.ROCK to Move.LOSE,
Move.PAPER to Move.DRAW,
Move.SCISSORS to Move.WIN,
),
Move.SCISSORS to mapOf(
Move.PAPER to Move.LOSE,
Move.SCISSORS to Move.DRAW,
Move.ROCK to Move.WIN,
),
)
fun convertMatrix() = buildMap {
matrix.toMutableMap().forEach {
put(
it.key,
buildMap {
it.value.forEach {
put(it.value, it.key)
}
}
)
}
}
enum class Move(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3),
LOSE(0),
DRAW(3),
WIN(6),
}
fun main() {
fun part1(input: List<String>): Int =
input.map {
it.split(" ").map {
when (it) {
"A", "X" -> Move.ROCK
"B", "Y" -> Move.PAPER
"C", "Z" -> Move.SCISSORS
else -> { throw IllegalArgumentException() }
}
}
}.map {
it.last().score + matrix.getValue(it.first()).getValue(it.last()).score
}.sum()
fun part2(input: List<String>): Int =
input.map {
it.split(" ").map {
when (it) {
"A" -> Move.ROCK
"B" -> Move.PAPER
"C" -> Move.SCISSORS
"X" -> Move.LOSE
"Y" -> Move.DRAW
"Z" -> Move.WIN
else -> { throw IllegalArgumentException() }
}
}
}.map {
it.last().score + convertMatrix().getValue(it.first()).getValue(it.last()).score
}.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
check(part2(testInput) == 12)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e26cd35ef64fcedc4c6e40b97a63d7c1332bb61f | 2,122 | advent-of-code | Apache License 2.0 |
codeforces/kotlinheroes4/i.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes4
fun main() {
val (n, m, _, sIn) = readInts()
val s = sIn - 1
val a = readInts()
val inf = n * n * n
val e = List(n) { IntArray(n) { inf } }
repeat(m) {
val (u, v) = readInts().map { it - 1 }
e[u][v] = 1
}
for (k in e.indices) for (i in e.indices) for (j in e.indices) e[i][j] = minOf(e[i][j], e[i][k] + e[k][j])
val sum = List(1 shl n) { mask -> mask.oneIndices().sumOf { a[it].toLong() } }
val sumAll = sum.last()
val len = List(n) { List(n) { IntArray(1 shl n) { inf } } }
for (mask in 0 until (1 shl n)) {
val indices = mask.oneIndices()
if (indices.size == 1) len[indices[0]][indices[0]][mask] = 0
for (i in indices) for (j in indices) if (i != j) {
len[i][j][mask] = indices.minOf { k -> len[i][k][mask xor (1 shl j)] + e[k][j] }
}
}
val eat = List(n) { i ->
val map = java.util.TreeMap(mapOf(0L to 0, Long.MAX_VALUE to inf))
for (mask in sum.indices) if (mask.hasBit(i)) for (j in e.indices) if (mask.hasBit(j)) {
val eat = sum[mask]
val edges = len[i][j][mask]
if (map.ceilingEntry(eat)!!.value!! <= edges) continue
map[eat] = edges
while (true) {
val prevEntry = map.floorEntry(eat - 1) ?: break
if (prevEntry.value!! < edges) break
map.remove(prevEntry.key!!)
}
}
map
}
val best = mutableListOf(IntArray(n) { inf }.also { it[s] = 0 })
val seen = mutableMapOf<List<Int>, Pair<Int, Int>>()
val period: Int; val periodEdges: Int
while (true) {
val prev = best.last()
val next = IntArray(n) { i -> e.indices.minOf { j -> prev[j] + len[j][i].last() } }
best.add(next)
val nextMin = next.minOrNull()!!
val snapshot = next.map { it - nextMin }
if (snapshot in seen) {
period = seen.size - seen[snapshot]!!.first
periodEdges = nextMin - seen[snapshot]!!.second
break
}
seen[snapshot] = seen.size to nextMin
}
println(readLongs().map { c ->
val i = c / sumAll
val toTake = c - sumAll * i
val takePeriods = maxOf(i - best.size + period, 0) / period
val bestI = best[(i - takePeriods * period).toInt()]
takePeriods * periodEdges + e.indices.minOf { j -> bestI[j] + eat[j].ceilingEntry(toTake)!!.value!! }
}.joinToString("\n"))
}
private fun Int.bit(index: Int) = shr(index) and 1
private fun Int.hasBit(index: Int) = bit(index) != 0
private fun Int.oneIndices() = (0 until countSignificantBits()).filter { (this shr it) and 1 != 0 }
private fun Int.countSignificantBits() = Int.SIZE_BITS - Integer.numberOfLeadingZeros(this)
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private fun readLongs() = readStrings().map { it.toLong() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,675 | competitions | The Unlicense |
src/aoc2022/day02/Day02.kt | svilen-ivanov | 572,637,864 | false | {"Kotlin": 53827} | package aoc2022.day02
import aoc2022.day02.Outcome.*
import readInput
enum class RockPaperScissors(
val otherSymbol: String,
val mySymbol: String,
val myScore: Int,
val order: Int,
) {
ROCK("A", "X", 1, 1),
SCISSORS("C", "Z", 3, 2),
PAPER("B", "Y", 2, 3),
}
enum class Outcome(val symbol: String) {
WIN("Z"),
TIE("Y"),
LOSE("X")
}
object Game {
private val all = RockPaperScissors.values().toList().sortedBy(RockPaperScissors::order)
private fun RockPaperScissors.getOutcome(other: RockPaperScissors): Outcome {
if (this == other) {
return TIE
}
val winsOver = getWinsOver()
return if (other == winsOver) {
WIN
} else {
LOSE
}
}
private fun RockPaperScissors.getWinsOver(): RockPaperScissors {
val index = all.indexOf(this)
val isLast = index == all.size - 1
val winsOver = if (isLast) {
all.first()
} else {
all[index + 1]
}
return winsOver
}
private fun RockPaperScissors.getLoosesFrom(): RockPaperScissors {
val index = all.indexOf(this)
val isFirst = index == 0
val losesFrom = if (isFirst) {
all.last()
} else {
all[index - 1]
}
return losesFrom
}
fun scoreGame(me: RockPaperScissors, other: RockPaperScissors) = when (me.getOutcome(other)) {
WIN -> 6
TIE -> 3
LOSE -> 0
}
fun getMyMoveOnOutcome(expectedOutcome: Outcome, otherMove: RockPaperScissors) =
when (expectedOutcome) {
WIN -> otherMove.getLoosesFrom()
TIE -> otherMove
LOSE -> otherMove.getWinsOver()
}
}
val convertFromOtherSymbol = RockPaperScissors.values().associateBy { it.otherSymbol }
val convertFromMySymbol = RockPaperScissors.values().associateBy { it.mySymbol }
val convertOutcome = Outcome.values().associateBy { it.symbol }
fun main() {
fun part1(input: List<String>) {
var sum = 0
for (line in input) {
val (otherSymbol, mySymbol) = line.split(" ")
val otherMove = convertFromOtherSymbol[otherSymbol]!!
val myMove = convertFromMySymbol[mySymbol]!!
val score = Game.scoreGame(myMove, otherMove) + myMove.myScore
sum += score
}
println("$sum")
check(sum == 15632)
}
fun part2(input: List<String>) {
var sum = 0
for (line in input) {
val (otherSymbol, expectedOutcomeSymbol) = line.split(" ")
val otherMove = convertFromOtherSymbol[otherSymbol]!!
val expectedOutcome = convertOutcome[expectedOutcomeSymbol]!!
val myMove = Game.getMyMoveOnOutcome(expectedOutcome, otherMove)
val score = Game.scoreGame(myMove, otherMove) + myMove.myScore
sum += score
}
println("$sum")
check(sum == 14416)
}
val testInput = readInput("day02/day02")
part1(testInput)
part2(testInput)
}
| 0 | Kotlin | 0 | 0 | 456bedb4d1082890d78490d3b730b2bb45913fe9 | 3,081 | aoc-2022 | Apache License 2.0 |
src/adventofcode/day02/Day02.kt | bstoney | 574,187,310 | false | {"Kotlin": 27851} | package adventofcode.day02
import adventofcode.AdventOfCodeSolution
fun main() {
Solution.solve()
}
object Solution : AdventOfCodeSolution<Int>() {
override fun solve() {
solve(2, 15, 12)
}
override fun part1(input: List<String>): Int {
return getRounds(input) { _: Play, playerInput: String ->
when (playerInput) {
"X" -> Play.A
"Y" -> Play.B
"Z" -> Play.C
else -> throw IllegalArgumentException("Illegal player input: $playerInput")
}
}
.sumOf { it.roundScore() }
}
override fun part2(input: List<String>): Int {
return getRounds(input) { opponentPlay: Play, playerInput: String ->
when (playerInput) {
"X" -> opponentPlay.defeats()
"Y" -> opponentPlay
"Z" -> opponentPlay.defeatedBy()
else -> throw IllegalArgumentException("Illegal player input: $playerInput")
}
}
.sumOf { it.roundScore() }
}
private fun getRounds(
input: List<String>,
playerMove: (opponentInput: Play, playerInput: String) -> Play
): List<Round> = input
.filter { it.length == 3 }
.map { it.split(" ") }
.map { (opponentInput, playerInput) ->
val opponentPlay = Play.valueOf(opponentInput)
val round = Round(opponentPlay, playerMove(opponentPlay, playerInput))
debug("${round.opponent.move} ($opponentInput) vs ${round.player.move} ($playerInput): ${round.roundResult()} + ${round.player.move} = ${round.roundScore()}")
round
}
private data class Round(val opponent: Play, val player: Play) {
fun roundResult() = opponent.playAgainst(player)
fun roundScore() = roundResult().score + player.move.score
}
private enum class RoundResult(val score: Int) {
Win(6),
Draw(3),
Lose(0),
;
}
private enum class Play(val move: Move) {
A(Move.Rock),
B(Move.Paper),
C(Move.Scissors),
;
fun playAgainst(play: Play): RoundResult =
when (play.move) {
this.move -> RoundResult.Draw
defeats().move -> RoundResult.Lose
else -> RoundResult.Win
}
fun defeats(): Play = when (move) {
Move.Rock -> C
Move.Paper -> A
Move.Scissors -> B
}
fun defeatedBy(): Play = when (move) {
Move.Rock -> B
Move.Paper -> C
Move.Scissors -> A
}
}
private enum class Move(val score: Int) {
Rock(1),
Paper(2),
Scissors(3),
}
}
| 0 | Kotlin | 0 | 0 | 81ac98b533f5057fdf59f08940add73c8d5df190 | 2,765 | fantastic-chainsaw | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2022/Day16.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 16 - Proboscidea Volcanium
* Problem Description: http://adventofcode.com/2022/day/16
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day16/
*/
package com.ginsberg.advent2022
import com.github.shiguruikai.combinatoricskt.combinations
import com.github.shiguruikai.combinatoricskt.permutations
class Day16(input: List<String>) {
private val rooms: Map<String, ValveRoom> = input.map { ValveRoom.of(it) }.associateBy { it.name }
private val cheapestPathCosts: Map<String, Map<String, Int>> = calculateShortestPaths()
fun solvePart1(): Int = searchPaths("AA", 30)
fun solvePart2(): Int =
cheapestPathCosts.keys.filter { it != "AA" }
.combinations(cheapestPathCosts.size / 2)
.map { it.toSet() }
.maxOf { halfOfTheRooms ->
searchPaths("AA", 26, halfOfTheRooms) + searchPaths("AA", 26, cheapestPathCosts.keys - halfOfTheRooms)
}
private fun searchPaths(
location: String,
timeAllowed: Int,
seen: Set<String> = emptySet(),
timeTaken: Int = 0,
totalFlow: Int = 0
): Int = cheapestPathCosts
.getValue(location)
.asSequence()
.filterNot { (nextRoom, _) -> nextRoom in seen }
.filter { (_, traversalCost) -> timeTaken + traversalCost + 1 < timeAllowed }
.maxOfOrNull { (nextRoom, traversalCost) ->
searchPaths(
nextRoom,
timeAllowed,
seen + nextRoom,
timeTaken + traversalCost + 1,
totalFlow + ((timeAllowed - timeTaken - traversalCost - 1) * rooms.getValue(nextRoom).flowRate)
)
} ?: totalFlow
private fun calculateShortestPaths(): Map<String, Map<String, Int>> {
val shortestPaths = rooms.values.associate {
it.name to it.paths.associateWith { 1 }.toMutableMap()
}.toMutableMap()
shortestPaths.keys.permutations(3).forEach { (waypoint, from, to) ->
shortestPaths[from, to] = minOf(
shortestPaths[from, to], // Existing Path
shortestPaths[from, waypoint] + shortestPaths[waypoint, to] // New Path
)
}
val zeroFlowRooms = rooms.values.filter { it.flowRate == 0 || it.name == "AA" }.map { it.name }.toSet()
shortestPaths.values.forEach { it.keys.removeAll(zeroFlowRooms) }
val canGetToFromAA: Set<String> = shortestPaths.getValue("AA").keys
return shortestPaths.filter { it.key in canGetToFromAA || it.key == "AA" }
}
private operator fun Map<String, MutableMap<String, Int>>.set(key1: String, key2: String, value: Int) {
getValue(key1)[key2] = value
}
private operator fun Map<String, Map<String, Int>>.get(key1: String, key2: String, defaultValue: Int = 31000): Int =
get(key1)?.get(key2) ?: defaultValue
private data class ValveRoom(val name: String, val paths: List<String>, val flowRate: Int) {
companion object {
fun of(input: String): ValveRoom =
ValveRoom(
input.substringAfter(" ").substringBefore(" "),
input.substringAfter("valve").substringAfter(" ").split(", "),
input.substringAfter("=").substringBefore(";").toInt()
)
}
}
}
| 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 3,433 | advent-2022-kotlin | Apache License 2.0 |
src/Day15.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} | @file:Suppress("PackageDirectoryMismatch")
package day15
import readInput
import kotlin.math.*
data class Pos(val x:Int, val y: Int)
fun Pos.distance(p: Pos) = abs(p.x-x)+abs(p.y-y)
data class Sensor(val pos: Pos, val beacon: Pos){
val range = pos.distance(beacon)
val minX get() = pos.x - range
val maxX get() = pos.x + range
fun contains(x: Int, y: Int) = abs(pos.x-x)+abs(pos.y-y) <= range
}
const val INT = """(\-?\d+)"""
val sensorPattern = Regex("""Sensor at x=$INT, y=$INT: closest beacon is at x=$INT, y=$INT""")
fun Sensor(line: String): Sensor {
val (sx, sy, bx, by) = (sensorPattern.find(line) ?: error("invalid sensor $line"))
.destructured.toList()
.map { it.toInt() }
return Sensor(Pos(sx,sy), Pos(bx,by))
}
fun part1(lines: List<String>, y: Int): Int {
val sensors = lines.map { Sensor(it) }
val beacons = sensors.map { it.beacon }.toSet()
val res = (sensors.minOf { it.minX }..sensors.maxOf { it.maxX }).count { x ->
val p = Pos(x,y)
p !in beacons && sensors.any { it.pos.distance(p) <= it.range }
}
return res
}
class RangesUnion {
private data class Mark(val value: Int, var delta: Int)
private val marks = mutableListOf<Mark>()
fun addRange(from: Int, exclusiveTo: Int) {
if (from >= exclusiveTo) return
var i = 0
while (i < marks.size && from > marks[i].value) ++i
if (i<marks.size && marks[i].value == from) marks[i].delta +=1
else marks.add(i,Mark(from,1))
++i
while (i < marks.size && exclusiveTo > marks[i].value) ++i
if (i<marks.size && marks[i].value == exclusiveTo) marks[i].delta -=1
else marks.add(i,Mark(exclusiveTo,-1))
}
fun getFirstNotContainedIn(range: IntRange): Int? {
if (marks.isEmpty() || marks.first().value > range.first)
return range.first
check(marks.first().delta>0)
var inRange = 0
for(m in marks) {
inRange += m.delta
if (m.value > range.last) return null
if (inRange==0 && m.value >= range.first)
return m.value
}
return null
}
}
fun part2(lines: List<String>, max: Int): Long {
val sensors = lines.map { Sensor(it) }
for (y in 0..max) {
val excludes = RangesUnion()
sensors.forEach {
val d = abs(y-it.pos.y)
if ( d <= it.range) {
val dx = it.range - d
val x = it.pos.x
excludes.addRange(x-dx, x+dx+1)
}
}
val x = excludes.getFirstNotContainedIn(0..max)
if (x != null) return x * 4000000L + y
}
return -1
}
fun main() {
val testInput = readInput("Day15_test")
check(part1(testInput,10) == 26)
check(part2(testInput,20) == 56000011L)
val input = readInput("Day15")
println(part1(input,2000000)) // 5403290
println(part2(input,4000000)) // 10291582906626
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 2,962 | aoc2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day16.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
import aoc2022.utils.MazeToTarget
import java.lang.Integer.min
val parseValve = "Valve (\\S+) has flow rate=(\\d+); tunnels? leads? to valves? (.*)".toRegex()
data class LocationAndBusy(val valve: Valve, val time: Int)
data class Valve(val id: String, val rate: Int, val links: List<String>)
class Tunnels(private val valves: Map<String, Valve>) {
fun distance(from: Valve, to: Valve) : Int {
return distances(listOf(from), to).first().second
}
fun distances(froms: List<Valve>, to: Valve) : List<Pair<Valve, Int>> {
val maze = MazeToTarget(to) { pos -> pos.links.map { valves[it]!!}}
return froms.map {
it to maze.distanceFrom(it)
}
}
fun calculateDistances(
nonZeroValves: List<Valve>,
start: Valve
): HashMap<Pair<String, String>, Int> {
val distances = HashMap<Pair<String, String>, Int>()
for (v in nonZeroValves) {
distances(nonZeroValves + listOf(start), v).forEach { (valve, distance) ->
distances[valve.id to v.id] = distance - 1
}
}
return distances
}
}
fun main() {
val testInput = """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""".split("\n")
fun best_very_slow(start: Valve, valves: Map<String, Valve>, time: Int): Int {
if (time <= 0) return 0
return sequence {
if (start.rate > 0) {
val newVales = valves + (start.id to start.copy(rate=0))
start.links.forEach { linkId ->
yield((start.rate * (time-1)) + best_very_slow(valves[linkId]!!, newVales, time - 2))
}
}
else {
start.links.forEach { linkId ->
yield( best_very_slow(valves[linkId]!!, valves, time - 1))
}
}
}.max()
}
fun best(start: Valve, nonZeroValves: Set<Valve>, distances: Map<Pair<String, String>, Int>, time: Int): Int {
return nonZeroValves.maxOfOrNull {
val timeTaken = distances[start.id to it.id]!!
val newTime = time - (timeTaken + 1)
if (newTime > 0)
(newTime * it.rate) + best(it, nonZeroValves - it, distances, newTime)
else 0
} ?: 0
}
fun bestTwoPeople(positions: List<LocationAndBusy>,
nonZeroValves: Set<Valve>, distances: Map<Pair<String, String>, Int>, time: Int): Int {
val (start1, start2) = positions.sortedBy { it.time }
if (start1.time == 0) {
return nonZeroValves.maxOfOrNull {
val timeTaken = distances[start1.valve.id to it.id]!! + 1
val endTime = time - timeTaken
val timeStep = min(timeTaken, start2.time)
val newTime = time - timeStep
if (endTime > 0)
(endTime * it.rate) + bestTwoPeople(
listOf(
LocationAndBusy(it, timeTaken - timeStep),
start2.copy(time = start2.time - timeStep)
), nonZeroValves - it, distances, newTime
)
else 0
} ?: 0
}
return -1
}
fun part1(input: List<String>): Int {
val valves = input.parsedBy(parseValve) {
val (id, rate, links) = it.destructured
Valve(id, rate.toInt(), links.split(", "))
}.toList()
val valveMap = valves.associateBy { it.id }
val nonZeroValves = valves.filter { it.rate > 0 }
val tunnels = Tunnels(valveMap)
val start = valveMap["AA"]!!
val distances = tunnels.calculateDistances(nonZeroValves, start)
return best(start, nonZeroValves.toSet(), distances, 30)
}
fun part2(input: List<String>): Int {
val valves = input.parsedBy(parseValve) {
val (id, rate, links) = it.destructured
Valve(id, rate.toInt(), links.split(", "))
}.toList()
val valveMap = valves.associateBy { it.id }
val nonZeroValves = valves.filter { it.rate > 0 }
val tunnels = Tunnels(valveMap)
val start = valveMap["AA"]!!
val distances = tunnels.calculateDistances(nonZeroValves, start)
return bestTwoPeople(listOf(LocationAndBusy(start, 0), LocationAndBusy(start, 0)), nonZeroValves.toSet(), distances, 26)
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 1651)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 16).toList()
println(part1(puzzleInput))
println(part2(testInput))
println(part2(puzzleInput))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 5,320 | aoc-2022-kotlin | Apache License 2.0 |
src/day11/Day11_functional.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day11
import readLines
/**
* Credit goes to tginsberg (https://github.com/tginsberg/advent-2022-kotlin)
* I'm experimenting with his solutions to better learn functional programming in Kotlin.
* Files without the _functional suffix are my original solutions.
*/
private class MonkeyV2(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: Long,
val trueMonkey: Int,
val falseMonkey: Int
) {
var interactions: Long = 0
fun inspectItems(monkeys: List<MonkeyV2>, changeToWorryLevel: (Long) -> Long) {
items.forEach { item ->
val worry = changeToWorryLevel(operation(item))
val target = if (worry % test == 0L) trueMonkey else falseMonkey
monkeys[target].items.add(worry)
}
interactions += items.size
items.clear()
}
companion object {
fun of(input: List<String>): MonkeyV2 {
val items = input[1].substringAfter(": ").split(", ").map { it.toLong() }.toMutableList()
val operationValue = input[2].substringAfterLast(" ")
val operation: (Long) -> Long = when {
operationValue == "old" -> ({ it * it })
'*' in input[2] -> ({ it * operationValue.toLong() })
else -> ({ it + operationValue.toLong() })
}
val test = input[3].substringAfterLast(" ").toLong()
val trueMonkey = input[4].substringAfterLast(" ").toInt()
val falseMonkey = input[5].substringAfterLast(" ").toInt()
return MonkeyV2(
items,
operation,
test,
trueMonkey,
falseMonkey
)
}
}
}
private fun List<MonkeyV2>.business(): Long =
sortedByDescending { it.interactions }.let { it[0].interactions * it[1].interactions }
private fun rounds(monkeys: List<MonkeyV2>, numRounds: Int, changeToWorryLevel: (Long) -> Long) {
repeat(numRounds) {
monkeys.forEach { it.inspectItems(monkeys, changeToWorryLevel) }
}
}
fun part1(input: List<String>): Long {
val monkeys: List<MonkeyV2> = input.chunked(7).map { MonkeyV2.of(it) }
rounds(monkeys, 20) { it / 3 }
return monkeys.business()
}
fun part2(input: List<String>): Long {
val monkeys: List<MonkeyV2> = input.chunked(7).map { MonkeyV2.of(it) }
val testProduct: Long = monkeys.map { it.test }.reduce(Long::times)
rounds(monkeys, 10_000) { it % testProduct }
return monkeys.business()
}
fun main(){
println(part1(readLines("day11/test")))
println(part2(readLines("day11/test")))
println(part1(readLines("day11/input")))
println(part2(readLines("day11/input")))
} | 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 2,721 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day8.kt | nerok | 436,232,451 | false | {"Kotlin": 32118} | import java.io.File
import java.util.*
fun main(args: Array<String>) {
day8part2()
}
fun day8part1() {
val countArray = IntArray(8) { 0 }
val input = File("day8input.txt").bufferedReader().readLines()
input.map { line ->
line.split(" | ").map { it.split(" ") }.let { it.first() to it.last() }
}.map { entry ->
entry.first.groupBy { it.length } to entry.second.groupBy { it.length }
}.map { it.second }.forEach {
it.forEach {
countArray[it.key] += it.value.size
}
}
val countMap = countArray.mapIndexed { index, i -> index to i }.toMap()
println("Score: ${countMap[2]!!.plus(countMap[3]!!).plus(countMap[4]!!).plus(countMap[7]!!)}")
}
fun day8part2() {
val countArray = IntArray(8) { 0 }
val input = File("day8input.txt").bufferedReader().readLines()
input.map { line ->
line.split(" | ").map { it.split(" ") }.let { it.first().map { it.toSortedSet() } to it.last().map { it.toSortedSet() } }
}.map {
val map = predictPairs(it.first)
Integer.parseInt(it.second.map { map[it] }.let { it.joinToString("") })
}.also { println(it) }.also {
println(it.sum())
}
}
fun predictPairs(x: List<SortedSet<Char>>): MutableMap<SortedSet<Char>, Int> {
val map = x.associateWith { -1 }.toMutableMap()
map.forEach {
when (it.key.size) {
2 -> {
map[it.key] = 1
}
3 -> {
map[it.key] = 7
}
4 -> {
map[it.key] = 4
}
7 -> {
map[it.key] = 8
}
else -> {
}
}
}
map.filter { it.key.size == 6 }.forEach {
if (it.key.containsAll(map.filterValues { it == 4 }.keys.first())) {
map[it.key] = 9
} else if (it.key.containsAll(map.filterValues { it == 1 }.keys.first())) {
map[it.key] = 0
} else {
map[it.key] = 6
}
}
map.filter { it.value == -1 }.forEach {
if (it.key.containsAll(map.filterValues { it == 7 }.keys.first())) {
map[it.key] = 3
} else if (map.filterValues { it == 9 }.keys.first().containsAll(it.key)) {
map[it.key] = 5
} else {
map[it.key] = 2
}
}
return map
}
| 0 | Kotlin | 0 | 0 | 4dee925c0f003fdeca6c6f17c9875dbc42106e1b | 2,350 | Advent-of-code-2021 | MIT License |
advent-of-code-2022/src/Day18.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | fun main() {
val testInput = readInput("Day18_test")
val input = readInput("Day18")
"Part 1" {
part1(testInput) shouldBe 64
measureAnswer { part1(input) }
}
"Part 2" {
part2(testInput) shouldBe 58
measureAnswer { part2(input) }
}
}
private val directions = listOf(
listOf(0, 0, 1),
listOf(0, 0, -1),
listOf(0, 1, 0),
listOf(0, -1, 0),
listOf(1, 0, 0),
listOf(-1, 0, 0),
)
private fun part1(input: List<Cube>): Int {
val occupied = mutableSetOf<Cube>()
var connectedSides = 0
for (cube in input) {
connectedSides += directions.count { (dx, dy, dz) ->
val (x, y, z) = cube
Cube(x + dx, y + dy, z + dz) in occupied
} * 2
occupied += cube
}
return input.size * 6 - connectedSides
}
private fun part2(input: List<Cube>): Int {
val occupied = mutableSetOf<Cube>()
var maxX = 0
var maxY = 0
var maxZ = 0
for (cube in input) {
occupied += cube
maxX = maxOf(maxX, cube.x)
maxY = maxOf(maxY, cube.y)
maxZ = maxOf(maxZ, cube.z)
}
fun generateNeighbors(cube: Cube): Sequence<Cube> = sequence {
val (x, y, z) = cube
if (x >= 0) yield(Cube(x - 1, y, z))
if (x <= maxX) yield(Cube(x + 1, y, z))
if (y >= 0) yield(Cube(x, y - 1, z))
if (y <= maxY) yield(Cube(x, y + 1, z))
if (z >= 0) yield(Cube(x, y, z - 1))
if (z <= maxZ) yield(Cube(x, y, z + 1))
}
var connectedSides = 0
val airCubes = mutableSetOf(Cube(0, 0, 0))
val queue = ArrayDeque<Cube>()
queue.addFirst(airCubes.first())
while (queue.isNotEmpty()) {
val cube = queue.removeFirst()
for (ncube in generateNeighbors(cube).filterNot { it in airCubes }) {
if (ncube in occupied) {
connectedSides++
} else {
airCubes += ncube
queue.addLast(ncube)
}
}
}
return connectedSides
}
private fun readInput(name: String) = readLines(name).map {
val (x, y, z) = it.splitInts()
Cube(x, y, z)
}
private data class Cube(val x: Int, val y: Int, val z: Int)
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 2,212 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Day8.kt | C06A | 435,034,782 | false | {"Kotlin": 20662} | package days
class Day8 : Day(8) {
override fun partOne(): Any {
return inputList.map {
it.split("|")[1]
}.map {
it.split(Regex("\\W"))
}.flatten(
).filter {
it.trim().length in setOf(2, 3, 4, 7)
}.count()
}
override fun partTwo(): Any {
return inputList.map {
it.split(
"|"
).map {
it.split(
Regex("\\W")
).map {
it.toByteArray().toSet()
}
}.let {
it[0] to it[1]
}
}.map { (sample, results) ->
(sample + results) to results
}.map { (whole, results) ->
/*
1 -- * * с * * f * -- 2 = 1
4 -- * b c d * f * -- 4 = 4
7 -- a * c * * f * -- 3 = 7
8 -- a b c d e f g -- 7 = 8
9 -- a b c d * f g -- 6 & includes 4
0 -- a b c * e f g -- 6 & includes 1
6 -- a b * d e f g -- 6 & not includes 1
3 -- a * c d * f g -- 5 & includes 1
2 -- a * c d e * g -- 5 & overlaps with 4 in 2 places
5 -- a b * d * f g -- 5 & overlaps with 4 in 3 places
*/
whole.distinct().filterNot { it.isNullOrEmpty() }.groupBy {
it.size
}.let { mapBySize ->
mapBySize.entries.fold(
mapOf(
mapBySize[2]!![0] to 1,
mapBySize[4]!![0] to 4,
mapBySize[3]!![0] to 7,
mapBySize[7]!![0] to 8
)
) { mapBySample, (len, samples) ->
if (samples.size > 1) {
samples.fold(mapBySample) { map, sample ->
map + Pair(sample, if (sample.containsAll(mapBySize[4]!![0])) {
9
} else if (sample.containsAll(mapBySize[2]!![0])) {
if (len == 6) {
0
} else {
3
}
} else {
if (len == 6) {
6
} else if ((sample - mapBySize[4]!![0]).size == 2) {
5
} else {
2
}
})
}
} else {
mapBySample
}
}.let {
results.filterNot {
it.isNullOrEmpty()
}.fold(0) { sum, indicator ->
sum * 10 + it[indicator]!!
}
}
}
}.sum()
}
}
| 0 | Kotlin | 0 | 0 | afbe60427eddd2b6814815bf7937a67c20515642 | 3,037 | Aoc2021 | Creative Commons Zero v1.0 Universal |
src/Day02.kt | oleksandrbalan | 572,863,834 | false | {"Kotlin": 27338} | fun main() {
val input = readInput("Day02")
.map {
val options = it.split(" ")
options[0] to options[1]
}
val roundsPart1 = input
.map { (first, second) ->
Round(
your = Option.from(second),
opponent = Option.from(first),
)
}
println("Part1: ${roundsPart1.sumOf { it.score }}")
val roundsPart2 = input
.map { (first, second) ->
val result = Result.from(second)
val opponent = Option.from(first)
Round(
your = Option.from(result, opponent),
opponent = opponent,
)
}
println("Part1: ${roundsPart2.sumOf { it.score }}")
}
private data class Round(
val your: Option,
val opponent: Option,
) {
private val result: Result =
when {
your == opponent -> Result.Draw
your.wins() == opponent -> Result.Win
else -> Result.Lose
}
val score: Int = your.score + result.score
}
private enum class Option(val score: Int) {
Rock(1),
Paper(2),
Scissors(3);
fun wins(): Option = get { it - 1 }
fun loses(): Option = get { it + 1 }
private fun get(op: (Int) -> Int): Option {
val size = values().size
return Option.values()[(op(ordinal) + size) % size]
}
companion object {
fun from(char: String): Option =
when (char) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> error("Option `$char` is not supported \uD83D\uDE40")
}
fun from(result: Result, opponent: Option): Option =
when (result) {
Result.Draw -> opponent
Result.Lose -> opponent.wins()
Result.Win -> opponent.loses()
}
}
}
private enum class Result(val score: Int) {
Lose(0),
Draw(3),
Win(6);
companion object {
fun from(char: String): Result =
when (char) {
"X" -> Lose
"Y" -> Draw
"Z" -> Win
else -> error("Result `$char` is not supported \uD83D\uDE40")
}
}
}
| 0 | Kotlin | 0 | 2 | 1493b9752ea4e3db8164edc2dc899f73146eeb50 | 2,275 | advent-of-code-2022 | Apache License 2.0 |
src/Day21/Day21.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day21
import readInput
import java.math.BigInteger
data class Node(val id: String, val nodeType: NodeType) {
enum class NodeType { LEAF, BRANCH }
var leafValue: BigInteger = BigInteger.ZERO
var nodeChildren: Pair<Node, Node>? = null
var nodeChildrenIds: Pair<String, String>? = null
var operation: String? = null
fun setNodeChildren(node1: Node, node2: Node) {
nodeChildren = Pair(node1, node2)
}
fun getValue(): BigInteger {
return when (nodeType) {
NodeType.LEAF -> leafValue
NodeType.BRANCH -> {
val firstValue = nodeChildren!!.first.getValue()
val secondValue = nodeChildren!!.second.getValue()
return when (operation) {
"+" -> firstValue + secondValue
"-" -> firstValue - secondValue
"*" -> firstValue * secondValue
"/" -> firstValue / secondValue
else -> {
print("AHHHHHHH")
BigInteger.ZERO
}
}
}
}
}
fun getAlgebraicEquation(): String {
return when (nodeType) {
NodeType.LEAF -> leafValue.toString()
NodeType.BRANCH -> {
val firstValue = nodeChildren!!.first.getAlgebraicEquation()
val secondValue = nodeChildren!!.second.getAlgebraicEquation()
return when (operation) {
"+" -> "($firstValue + $secondValue)"
"-" -> "($firstValue - $secondValue)"
"*" -> "($firstValue * $secondValue)"
"/" -> "($firstValue / $secondValue)"
"=" -> "($firstValue = $secondValue)"
else -> {
print("AHHHHHHH")
""
}
}
}
}
}
}
class MonkeySolver() {
var nodes = mutableMapOf<String, Node>()
fun readInput(input: List<String>) {
for (monkeyString in input) {
val monkeyStringSplit = monkeyString.split(" ")
val monkeyId = monkeyStringSplit[0].trimEnd(':')
val nodeType = if (monkeyStringSplit.count() == 4) Node.NodeType.BRANCH else Node.NodeType.LEAF
val node = Node(monkeyId, nodeType)
nodes[monkeyId] = node
when (nodeType) {
Node.NodeType.LEAF -> node.leafValue = monkeyStringSplit[1].toBigInteger()
Node.NodeType.BRANCH -> {
node.nodeChildrenIds = Pair(monkeyStringSplit[1], monkeyStringSplit[3])
node.operation = monkeyStringSplit[2]
}
}
}
}
fun matchNodes() {
for (id_node in nodes) {
if (id_node.value.nodeType == Node.NodeType.BRANCH) {
val node = id_node.value
node.nodeChildren = Pair(nodes[node.nodeChildrenIds!!.first]!!, nodes[node.nodeChildrenIds!!.second]!!)
}
}
}
}
fun main() {
fun part1(input: List<String>): BigInteger {
var monkeySolver = MonkeySolver()
monkeySolver.readInput(input)
monkeySolver.matchNodes()
return monkeySolver.nodes["root"]!!.getValue()
}
fun part2(input: List<String>): String {
var monkeySolver = MonkeySolver()
monkeySolver.readInput(input)
monkeySolver.matchNodes()
monkeySolver.nodes["root"]!!.operation = "="
return monkeySolver.nodes["root"]!!.getAlgebraicEquation()
}
val testInput = readInput("Day21","Day21_test")
// println(part1(testInput))
// check(part1(testInput) == 64)
// println(part2(testInput))
// check(part2(testInput) == 58)
val input = readInput("Day21","Day21")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 3,919 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | fouksf | 572,530,146 | false | {"Kotlin": 43124} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
fun parseInput(input: List<String>, lineNumber: Int): HashMap<Pair<Int, Int>, String> {
val map = HashMap<Pair<Int, Int>, String>()
for (line in input) {
val coordinates = line.replace("Sensor at", "")
.replace(" [x,y]=".toRegex(), "")
.split(": closest beacon is at")
.map { coords -> coords.split(",").map { it.toInt() } }
val x = coordinates[0][0]
val y = coordinates[0][1]
map[Pair(x, y)] = "S"
map[Pair(coordinates[1][0], coordinates[1][1])] = "B"
val manhattanDistance =
abs(x - coordinates[1][0]) + abs(y - coordinates[1][1])
for (dist in 1..manhattanDistance) {
for (i in 0..dist) {
val j = dist - i
if (y + j == lineNumber) {
for (p in listOf(
Pair(x + i, y + j),
Pair(x - i, y + j)
)) {
if (!map.contains(p)) {
map[p] = "#"
}
}
} else if (y - j == lineNumber) {
for (p in listOf(
Pair(x + i, y - j),
Pair(x - i, y - j)
)) {
if (!map.contains(p)) {
map[p] = "#"
}
}
}
}
}
}
return map
}
fun part1(map: HashMap<Pair<Int, Int>, String>, lineNumber: Int): Int {
return map.keys.filter { it.second == lineNumber }.count { map[it] == "#" }
}
fun part2(map: HashMap<Pair<Int, Int>, String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = parseInput(readInput("Day15_test"), 10)
println(part1(testInput, 10))
// println(part2(testInput))
val input = parseInput(readInput("Day15"), 2000000)
println(part1(input, 2000000))
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 701bae4d350353e2c49845adcd5087f8f5409307 | 2,291 | advent-of-code-2022 | Apache License 2.0 |
src/commonMain/kotlin/advent2020/day24/Day24Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day24
enum class Vector(val dx: Int, val dy: Int) {
E(2, 0),
W(-2, 0),
SE(1, 1),
SW(-1, 1),
NE(1, -1),
NW(-1, -1),
}
data class Position(val x: Int, val y: Int) {
operator fun plus(v: Vector) = Position(x + v.dx, y + v.dy)
override fun toString() = "($x,$y)"
}
fun part1(input: String): String {
val tiles = input.trim().lineSequence()
.map { line -> tile(line) }
.fold(emptySet<Position>()) { acc, tile -> if (tile in acc) acc - tile else acc + tile }
return tiles.size.toString()
}
fun part2(input: String): String {
var tiles = input.trim().lineSequence()
.map { line -> tile(line) }
.fold(emptySet<Position>()) { acc, tile -> if (tile in acc) acc - tile else acc + tile }
repeat(100) {
val neighbours = mutableMapOf<Position, Int>()
tiles.forEach { tile ->
Vector.values().forEach { v ->
neighbours[tile + v] = (neighbours[tile + v] ?: 0) + 1
}
}
tiles = neighbours
.filter { (tile, count) -> if (tile in tiles) count == 1 || count == 2 else count == 2 }
.keys
}
println(" Day 100: ${tiles.size} ")
return tiles.size.toString()
}
private fun tile(line: String) =
sequence {
var p = 0
while (p < line.length) {
when (line[p]) {
'e', 'w' -> yield(line.substring(p, p + 1)).also { p += 1 }
's', 'n' -> yield(line.substring(p, p + 2)).also { p += 2 }
else -> error("unknown `${line.drop(p)}` @ $p")
}
}
}
.map { Vector.valueOf(it.toUpperCase()) }
.fold(Position(0, 0)) { p, v -> p + v }
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 1,729 | advent-of-code-2020 | MIT License |
src/main/kotlin/days/Day5.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package days
import util.DayInput
class Day5 : Day("5") {
class Range(val start: Long, val length: Long) {
val end = start + length - 1
fun validValue(value: Long): Boolean {
return start <= value && value - start <= length - 1
}
fun intersect(otherRange: Range): Range? {
val start = Math.max(start, otherRange.start)
val end = Math.min(end, otherRange.end)
return fromStartEnd(start, end)
}
companion object {
fun fromStartEnd(start: Long, end: Long): Range? {
if (start <= end) {
return Range(start, end - start + 1)
}
return null
}
}
}
class MapRanges {
var sourceToTargetMapRanges = mutableListOf<MapRange>()
fun targetFromSource(source: Long): Long {
return sourceToTargetMapRanges.map { it.targetFromSource(source) }.filterNotNull().firstOrNull() ?: source
}
fun targetFromSource(source: Range): List<Range> {
val fold = sourceToTargetMapRanges.fold(Pair(listOf<Range>(source), listOf<Range>())) { acc, mapRange ->
val map = acc.first.map { mapRange.targetFromSource(it) }
val mapedRange = map.map { it.mappedRange }.filterNotNull()
val notFoundRange = map.flatMap { it.notFoundRange }
Pair(notFoundRange, acc.second + mapedRange)
}
return fold.first + fold.second
}
}
data class MapRange(val sourceStart: Long, val targetStart: Long, val length: Long) {
fun targetFromSource(source: Long): Long? {
if (sourceStart <= source && source - sourceStart <= length - 1) {
return targetStart + (source - sourceStart)
}
return null
}
class ConversionResult(val mappedRange: Range?, val notFoundRange: List<Range>)
fun targetFromSource(source: Range): ConversionResult {
val intersect = source.intersect(Range(sourceStart, length))
return if (intersect == null) {
ConversionResult(null, listOf(source))
} else {
ConversionResult(
Range(targetFromSource(intersect.start)!!, intersect.length),
listOf(
Range.fromStartEnd(source.start, intersect.start - 1),
Range.fromStartEnd(intersect.end + 1, source.end)
)
.filterNotNull()
)
}
}
}
class Map(val id: String, val source: String, val target: String) {
val mapRanges = MapRanges()
}
fun generateMap(dayInput: DayInput): MutableList<Map> {
return dayInput.inputList().subList(1, dayInput.inputList().size).fold(mutableListOf<Map>()) { acc, line ->
if (line.contains("map:")) {
val split = line.replace(" map:", "").split("-to-")
acc.add(Map(id = line, target = split[1], source = split[0]))
} else if (line.isNotEmpty()) {
val split = line.split(" ").map { it.toLong() }
acc.last().mapRanges.sourceToTargetMapRanges.add(
MapRange(
sourceStart = split[1],
targetStart = split[0],
length = split[2]
)
)
}
acc
}
}
override fun partOne(dayInput: DayInput): Any {
val inputList = dayInput.inputList()
val seeds = inputList[0].replace("seeds: ", "").split(" ").map { it.toLong() }
val map = generateMap(dayInput)
val result = seeds.map { seed ->
map.fold(seed) { acc, map ->
val targetFromSource = map.mapRanges.targetFromSource(acc)
println("seed $seed map ${map.id} source $acc target $targetFromSource")
targetFromSource
}
}
return result.min()
}
override fun partTwo(dayInput: DayInput): Any {
val seeds = dayInput.inputList()[0].replace("seeds: ", "").split(" ")
.map { it.toLong() }
.windowed(2, 2) {
Range(it[0], it[1])
}
val map = generateMap(dayInput)
val result = seeds.map { seed ->
map.fold(listOf(seed)) { acc, map ->
val flatMap = acc.flatMap { map.mapRanges.targetFromSource(it) }
flatMap
}
}
return result.flatMap { it }.map { it.start }.min()
}
}
fun main() {
Day5().run()
}
| 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 4,723 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/aoc/Day07.kt | fluxxion82 | 573,716,300 | false | {"Kotlin": 39632} | package aoc
import java.io.File
data class ElfFile(val name: String, val size: Long)
class Node(
val file: ElfFile,
val parent: Node?,
val children: MutableList<Node> = mutableListOf()
) {
val totalSize: Long = file.size + children.sumOf { it.totalSize }
}
fun parseTerminal(input: String, root: Node) {
var currentNode: Node? = root
input.split("\n").forEach {
when {
it.startsWith("\$") -> {
if (it.startsWith("$ cd")) {
if (it.startsWith("$ cd ..")) {
currentNode = currentNode?.parent
} else {
val dir = it.substringAfter("$ cd")
if (dir != "/") {
currentNode?.children?.forEach { node ->
if (node.file.name == dir.trim()) {
currentNode = node
}
}
}
}
}
}
else -> {
val (size, name) = it.split(" ")
val fileSize = if (size == "dir") 0 else size.toLong()
currentNode?.children?.add(Node(ElfFile(name, fileSize), currentNode))
}
}
}
}
fun treeSum(root: Node?): Long {
if (root == null) return 0
return root.totalSize + root.children.sumOf { treeSum(it) }
}
fun streamNodes(node: Node): Sequence<Node> = sequence {
yield((node))
node.children.forEach { child ->
yieldAll(streamNodes(child))
}
}
fun getDirSizes(root: Node) =
streamNodes(root).filter { it.file.size == 0L }.map { treeSum(it) }.toList().sorted()
fun main() {
val testInput = File("src/Day07_test.txt").readText()
val input = File("src/Day07.txt").readText()
fun part1(input: String): Long {
val disk = Node(ElfFile("/", 0), parent = null)
parseTerminal(input, disk)
val dirs = getDirSizes(disk)
return dirs.takeWhile { it <= 100000L }.sum()
}
fun part2(input: String): Long {
val disk = Node(ElfFile("/", 0), parent = null)
parseTerminal(input, disk)
val dirs = getDirSizes(disk)
return dirs.first { it > dirs.last() - 40000000L }
}
println("part one test: ${part1(testInput)}") // 95437
println("part one: ${part1(input)}") // 1770595
println("part two test: ${part2(testInput)}") // 24933642
println("part two: ${part2(input)}") // 2195372
}
| 0 | Kotlin | 0 | 0 | 3920d2c3adfa83c1549a9137ffea477a9734a467 | 2,548 | advent-of-code-kotlin-22 | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2022/day03/RucksackReorganization.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day03
import com.barneyb.aoc.util.Solver
fun main() {
Solver.execute(
::parse,
::partOne,
::partTwo,
)
}
internal data class Rucksack(
val left: Set<Int>,
val right: Set<Int>,
) {
val intersection = left.intersect(right).first()
fun contains(n: Int) =
left.contains(n) || right.contains(n)
}
internal fun parse(input: String) =
input.trim().lines().map { content ->
assert(content.length % 2 == 0) {
"odd number (${content.length}) of rucksack items: '$content'?!"
}
val priorities = buildList(content.length) {
for (c in content) {
add(c - (if (c < 'a') 'A' - 26 else 'a') + 1)
}
}
(priorities.size / 2).let { mid ->
Rucksack(
HashSet(priorities.subList(0, mid)),
HashSet(priorities.subList(mid, priorities.size)),
)
}
}
internal fun partOne(sacks: Collection<Rucksack>) =
sacks.sumOf(Rucksack::intersection)
internal fun partTwo(sacks: Collection<Rucksack>): Int {
assert(sacks.size % 3 == 0) {
"Non-multiple of three (${sacks.size}) number of elves?!"
}
return sacks.windowed(3, 3).sumOf(::badge)
}
internal fun badge(sacks: List<Rucksack>): Int {
val first = sacks.first()
val rest = sacks.subList(1, sacks.size)
for (n in (first.left + first.right)) {
if (rest.all { it.contains(n) }) {
return n
}
}
throw IllegalArgumentException("No shared item found?!")
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 1,596 | aoc-2022 | MIT License |
src/main/kotlin/Day2.kt | ryanclanigan | 440,047,375 | false | {"Kotlin": 8400} | import java.io.File
enum class Direction {
UP,
DOWN,
FORWARD
}
class SubmarineCommand(val direction: Direction, val magnitude: Int)
fun parseSubmarineCommand(command: String): SubmarineCommand {
val pieces = command.split(" ")
if (pieces.size != 2) throw Exception("Ruh roh")
return SubmarineCommand(Direction.valueOf(pieces[0].uppercase()), pieces[1].toInt())
}
fun day2Puzzle1() {
class Grid(val depth: Int, val horizontal: Int) {
fun applyCommand(command: SubmarineCommand) =
when (command.direction) {
Direction.UP -> Grid(depth - command.magnitude, horizontal)
Direction.DOWN -> Grid(depth + command.magnitude, horizontal)
Direction.FORWARD -> Grid(depth, horizontal + command.magnitude)
}
}
File("day2.txt").readLines()
.filter { it.isNotEmpty() }
.map { parseSubmarineCommand(it) }
.fold(Grid(0, 0)) { current, command -> current.applyCommand(command) }
.let { println(it.depth * it.horizontal) }
}
fun day2Puzzle2() {
class Grid(val depth: Int, val horizontal: Int, val aim: Int) {
fun applyCommand(command: SubmarineCommand) =
when (command.direction) {
Direction.UP -> Grid(depth, horizontal, aim - command.magnitude)
Direction.DOWN -> Grid(depth, horizontal, aim + command.magnitude)
Direction.FORWARD -> Grid(depth + aim * command.magnitude, horizontal + command.magnitude, aim)
}
}
File("day2.txt").readLines()
.filter { it.isNotEmpty() }
.map { parseSubmarineCommand(it) }
.fold(Grid(0, 0, 0)) { current, command -> current.applyCommand(command) }
.let { println(it.depth * it.horizontal) }
}
fun day3Puzzle2() {
val numbers = File("day3.txt").readLines()
.filter { it.isNotEmpty() }
val length = numbers[0].length
var sublist = numbers
(0..length).forEach {
if (sublist.size == 1) return@forEach
sublist = findSubListForCategory(Category.MOST, it, sublist)
}
val most = sublist[0].toInt(2)
sublist = numbers
(0..length).forEach {
if (sublist.size == 1) return@forEach
sublist = findSubListForCategory(Category.LEAST, it, sublist)
}
val least = sublist[0].toInt(2)
println(most * least)
}
fun findSubListForCategory(category: Category, index: Int, list: List<String>): List<String> {
var oneCount = 0
var zeroCount = 0
list.forEach { if (it[index] == '0') zeroCount += 1 else oneCount += 1 }
return when (category) {
Category.MOST -> list.filter {
val filterFor = if (oneCount >= zeroCount) '1' else '0'
it[index] == filterFor
}
Category.LEAST -> list.filter {
val filterFor = if (oneCount < zeroCount) '1' else '0'
it[index] == filterFor
}
}
}
enum class Category {
MOST,
LEAST
}
| 0 | Kotlin | 0 | 0 | 766fa81b4085a79feb98cef840ac9f4361d43e73 | 2,976 | AdventOfCode2021 | MIT License |
program/program/find-the-adjoint-of-a-matrix/FindTheAdjointOfAMatrix.kt | codinasion | 646,154,989 | false | {"TypeScript": 1253398, "JavaScript": 300972, "Java": 117345, "C#": 113493, "C": 108834, "C++": 108619, "Go": 71308, "Kotlin": 67478, "Python": 61284, "PHP": 60087, "Rust": 55932, "Swift": 49088, "Scala": 43272, "Ruby": 42267, "Dart": 41951, "R": 37264, "Perl": 33321, "Julia": 29785, "F#": 25527, "Haskell": 22115, "Shell": 5229, "CSS": 5171, "Raku": 4785, "Rebol": 25} | fun main() {
val matrixA = listOf(
listOf(1, 2, 3),
listOf(4, 5, 6),
listOf(7, 8, 9)
)
val matrixAdjoint = calculateAdjoint(matrixA)
println("Input (A): $matrixA")
println("Matrix of Adjoint (A*): $matrixAdjoint")
}
fun calculateAdjoint(matrix: List<List<Int>>): List<List<Int>> {
val matrixCofactors = calculateCofactors(matrix)
return transpose(matrixCofactors)
}
fun calculateCofactors(matrix: List<List<Int>>): List<List<Int>> {
return matrix.mapIndexed { i, row ->
row.indices.map { j ->
getCofactor(matrix, i, j)
}
}
}
fun transpose(matrix: List<List<Int>>): List<List<Int>> {
if (matrix.isEmpty() || matrix[0].isEmpty())
return emptyList()
val numRows = matrix.size
val numCols = matrix[0].size
return List(numCols) { col ->
List(numRows) { row ->
matrix[row][col]
}
}
}
fun getCofactor(matrix: List<List<Int>>, row: Int, col: Int): Int {
val sign = if ((row + col) % 2 == 0) 1 else -1
val subMatrix = getSubMatrix(matrix, row, col)
return sign * determinant(subMatrix)
}
fun getSubMatrix(matrix: List<List<Int>>, rowToRemove: Int, colToRemove: Int): List<List<Int>> {
return matrix
.filterIndexed { i, _ -> i != rowToRemove }
.map { row -> row.filterIndexed { j, _ -> j != colToRemove } }
}
fun determinant(matrix: List<List<Int>>): Int {
if (matrix.size == 2)
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
return matrix.indices.sumOf { i ->
val sign = if (i % 2 == 0) 1 else -1
val subMatrix = getSubMatrix(matrix, 0, i)
sign * matrix[0][i] * determinant(subMatrix)
}
} | 951 | TypeScript | 141 | 45 | 98267f35088871b601c609ce125f08a49c543adc | 1,728 | codinasion | MIT License |
kotlin/src/main/kotlin/AoC_Day7.kt | sviams | 115,921,582 | false | null |
object AoC_Day7 {
data class TreeNode(val name: String, val weight: Int, val totalWeight: Int, val children: List<String>)
private fun parseUnweighted(input: List<String>) : List<TreeNode> =
input.map {
val split = it.split(" ")
TreeNode(split[0], split[1].substring(1, split[1].length - 1).toInt(), 0, if (split.size > 2) split.subList(3,split.size).map { it.trim(',') } else listOf())
}
private fun mapWeights(tree: List<TreeNode>) : List<TreeNode> =
tree.map { TreeNode(it.name, it.weight, it.weight + resolveChildrenWeight(tree, it), it.children) }
private fun resolveChildrenWeight(all: List<TreeNode>, current: TreeNode) : Int {
val children = all.filter { current.children.contains(it.name) }
return children.fold(0) {acc, value -> acc + value.weight + resolveChildrenWeight(all, value) }
}
private tailrec fun balanceChildren(all: List<TreeNode>, node: TreeNode, lastDiff: Int) : Int {
val children = all.filter { node.children.contains(it.name) }
val childWeights = children.map { it.totalWeight }
val unbalancedChild = children.firstOrNull { child -> childWeights.count { it == child.totalWeight } == 1 }
return if (unbalancedChild == null)
node.weight - lastDiff
else
balanceChildren(all, unbalancedChild, childWeights.max()!! - childWeights.min()!!)
}
fun solvePt1(input: List<String>) : String {
val weightedTree = mapWeights(parseUnweighted(input))
return weightedTree.maxBy { it.totalWeight }!!.name
}
fun solvePt2(input: List<String>) : Int {
val newTree = mapWeights(parseUnweighted(input))
val rootName = newTree.maxBy { it.totalWeight }!!.name
val rootNode = newTree.firstOrNull { it.name == rootName }!!
return balanceChildren(newTree, rootNode, 0)
}
} | 0 | Kotlin | 0 | 0 | 19a665bb469279b1e7138032a183937993021e36 | 1,904 | aoc17 | MIT License |
src/Day03.kt | VadimB95 | 574,449,732 | false | {"Kotlin": 19743} | import java.lang.IllegalArgumentException
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val allCommonItems = mutableListOf<Char>()
input.forEach { rucksackInput ->
val itemsCount = rucksackInput.length
val compartment1 = rucksackInput.substring(0, itemsCount / 2).toSet()
val compartment2 = rucksackInput.substring(itemsCount / 2, rucksackInput.length).toSet()
val commonItems = compartment1.intersect(compartment2)
allCommonItems.addAll(commonItems)
}
return allCommonItems.sumOf { it.convertToPriority() }
}
private fun part2(input: List<String>): Int {
val groups = input.chunked(3)
val badges = mutableListOf<Char>()
groups.forEach { group ->
val badge = group[0].toSet().intersect(group[1].toSet()).intersect(group[2].toSet()).first()
badges.add(badge)
}
return badges.sumOf { it.convertToPriority() }
}
private fun Char.convertToPriority(): Int {
return when (this) {
in ('a'..'z') -> code - 96
in ('A'..'Z') -> code - 38
else -> throw IllegalArgumentException()
}
}
| 0 | Kotlin | 0 | 0 | 3634d1d95acd62b8688b20a74d0b19d516336629 | 1,390 | aoc-2022 | Apache License 2.0 |
src/day22/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day22
import assert
import println
import readInput
import java.util.*
data class Brick(val index: Int, var x: IntRange, var y: IntRange, var z: IntRange) {
val top by lazy { copy(z = z.last..z.last) }
val bottom by lazy { copy(z = z.first..z.first) }
val holding = mutableListOf<Brick>()
val standingOn = mutableListOf<Brick>()
fun intersects(brick: Brick) =
x.intersect(brick.x).isNotEmpty() &&
y.intersect(brick.y).isNotEmpty() &&
z.intersect(brick.z).isNotEmpty()
fun moveDown(steps: Int = 1): Brick = copy(z = (z.first - steps)..(z.last - steps))
}
class SandSlabs(input: List<String>) {
private var bricks = input.mapIndexed{ index, row ->
val (point1, point2) = row.split("~")
val (x1, y1, z1) = point1.split(",").map{it.toInt()}
val (x2, y2, z2) = point2.split(",").map{it.toInt()}
Brick(index, x1..x2,y1..y2, z1..z2)
}.sortedWith(compareBy { it.z.first })
init {
fun settle(settledBricks: MutableList<Brick>, brick: Brick): MutableList<Brick> {
var holdingBricks = listOf<Brick>()
var bottom = brick.bottom
while (bottom.z.first != 0 && holdingBricks.isEmpty()) {
bottom = bottom.moveDown()
holdingBricks = settledBricks.filter { it.top.intersects(bottom) }
}
val settledBrick = brick.moveDown(brick.z.first - bottom.z.first - 1)
holdingBricks.forEach {
it.holding += settledBrick
settledBrick.standingOn += it
}
settledBricks += settledBrick
return settledBricks
}
bricks = bricks.fold(mutableListOf(), ::settle).sortedWith(compareBy { it.z.first })
}
fun calculateSafelyRemovable(): Int {
return bricks.count { brick -> brick.holding.isEmpty() || brick.holding.all { it.standingOn.size > 1 } }
}
fun calculateMaxNumberOfFall(): Int {
fun countMovedBricksIfDisintegrated(brick: Brick): Int {
val movedBricks = mutableSetOf(brick.index)
val queue: Queue<Brick> = LinkedList()
brick.holding.forEach(queue::offer)
while (queue.isNotEmpty()) {
val brickToCheck = queue.poll()
if (brickToCheck.standingOn.all { movedBricks.contains(it.index) }) {
movedBricks.add(brickToCheck.index)
brickToCheck.holding.forEach(queue::offer)
}
}
movedBricks.remove(brick.index)
return movedBricks.size
}
return bricks.map(::countMovedBricksIfDisintegrated).sum()
}
}
fun main() {
SandSlabs(readInput("day22/test1"))
.calculateSafelyRemovable()
.assert(5)
"Part 1:".println()
SandSlabs(readInput("day22/input"))
.calculateSafelyRemovable()
.assert(501)
.println()
SandSlabs(readInput("day22/test1"))
.calculateMaxNumberOfFall()
.assert(7)
"Part 2:".println()
SandSlabs(readInput("day22/input"))
.calculateMaxNumberOfFall()
.assert(80948)
.println()
} | 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 3,194 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/de/niemeyer/aoc2022/Day11.kt | stefanniemeyer | 572,897,543 | false | {"Kotlin": 175820, "Shell": 133} | /**
* Advent of Code 2022, Day 11: Monkey in the Middle
* Problem Description: https://adventofcode.com/2022/day/11
*/
package de.niemeyer.aoc2022
import de.niemeyer.aoc.utils.Resources.resourceAsText
import de.niemeyer.aoc.utils.getClassName
import de.niemeyer.aoc.utils.product
fun main() {
fun solve(input: String, rounds: Int, adjust: (Long) -> Long): Long {
val monkeys = Monkey.parse(input).toMutableList()
repeat(rounds) {
for (idx in 0 until monkeys.size) {
val monkey = monkeys[idx]
val newWorryLevels = monkey.items.map {
adjust(monkey.increaseLevel(it))
}
newWorryLevels.forEach {
val target = monkey.test.targetMoneky(it)
monkeys[target].items.add(it)
}
monkey.itemCounter += monkey.items.size
monkey.items.removeIf { true }
monkeys[idx] = monkey
}
}
return monkeys.sortedBy { it.itemCounter }.takeLast(2).map { it.itemCounter }.product()
}
fun part1(input: String): Long =
solve(input, 20) { level -> level / 3 }
fun part2(input: String): Long {
val gcd = Monkey.parse(input).map { it.test.divider }.product()
return solve(input, 10_000) { level -> level % gcd }
}
val name = getClassName()
val testInput = resourceAsText(fileName = "${name}_test.txt").trim()
val puzzleInput = resourceAsText(fileName = "${name}.txt").trim()
check(part1(testInput) == 10_605L)
val puzzleResultPart1 = part1(puzzleInput)
println(puzzleResultPart1)
check(puzzleResultPart1 == 117_640L)
check(part2(testInput) == 2_713_310_158L)
val puzzleResultPart2 = part2(puzzleInput)
println(puzzleResultPart2)
check(puzzleResultPart2 == 30_616_425_600L)
}
data class MonkeyTest(val divider: Long, val trueMonkey: Int, val falseMonkey: Int) {
fun targetMoneky(level: Long) =
if (level % divider == 0L) trueMonkey else falseMonkey
}
data class Monkey(
val items: ArrayDeque<Long>,
val increaseLevel: (Long) -> Long,
val test: MonkeyTest,
var itemCounter: Long = 0L
) {
companion object {
fun parse(input: String): List<Monkey> =
input.split("\n\n")
.map { of(it.lines()) }
fun of(rules: List<String>): Monkey {
val inpItems = rules[1].substringAfter(": ").split(", ").map { it.toLong() }
val opElements = rules[2].split(" ")
val inpOperation = opElements.dropLast(1).last()
val inpOperand = opElements.last()
val levelFun = when (inpOperation) {
"+" -> { x: Long -> x + inpOperand.toLong() }
"*" -> when (inpOperand) {
"old" -> { x: Long -> x * x }
else -> { x: Long -> x * inpOperand.toLong() }
}
else -> error("Operation '${inpOperation}' is not supported")
}
val divider = rules[3].substringAfter("divisible by ").toLong()
val trueMonkey = rules[4].substringAfter("monkey ").toLong()
val falseMonkey = rules[5].substringAfter("monkey ").toLong()
return Monkey(
items = ArrayDeque(inpItems),
levelFun,
MonkeyTest(divider, trueMonkey.toInt(), falseMonkey.toInt())
)
}
}
}
| 0 | Kotlin | 0 | 0 | ed762a391d63d345df5d142aa623bff34b794511 | 3,475 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/Day21.kt | clechasseur | 318,029,920 | false | null | import org.clechasseur.adventofcode2020.Day21Data
object Day21 {
private val input = Day21Data.input
private val foodRegex = """^([a-z]+(?: [a-z]+)*) \(contains ([a-z]+(?:, [a-z]+)*)\)$""".toRegex()
fun part1(): Int {
val allFood = input.lines().map { it.toFood() }
val allergenMap = buildAllergenMap(allFood)
return allFood.flatMap { it.ingredients }.count { it !in allergenMap.values }
}
fun part2(): String {
val allFood = input.lines().map { it.toFood() }
val allergenMap = buildAllergenMap(allFood)
return allergenMap.entries.sortedBy { it.key }.joinToString(",") { it.value }
}
private fun buildAllergenMap(allFood: List<Food>): Map<String, String> {
val allergenMap = mutableMapOf<String, String>()
val allAllergens = allFood.flatMap { it.allergens }.toMutableSet()
while (allAllergens.isNotEmpty()) {
allAllergens.associateWith { allergen ->
val foodWithAllergen = allFood.filter { it.allergens.contains(allergen) }
foodWithAllergen.flatMap {
it.ingredients
}.distinct().filter { ingredient ->
foodWithAllergen.all { it.ingredients.contains(ingredient) } && ingredient !in allergenMap.values
}
}.filterValues { it.size == 1 }.forEach { (allergen, candidateIngredients) ->
allergenMap[allergen] = candidateIngredients.single()
allAllergens.remove(allergen)
}
}
return allergenMap
}
private data class Food(val ingredients: List<String>, val allergens: List<String>)
private fun String.toFood(): Food {
val match = foodRegex.matchEntire(this) ?: error("Invalid food: $this")
val (ingredients, allergens) = match.destructured
return Food(ingredients.split(" "), allergens.split(", "))
}
}
| 0 | Kotlin | 0 | 0 | 6173c9da58e3118803ff6ec5b1f1fc1c134516cb | 1,929 | adventofcode2020 | MIT License |
src/main/kotlin/aoc2023/Day07.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
class Day07 {
fun part1(input: List<String>): Long {
val sortedCards = input.map { parseCameCard(it, isJokerRule = false) }.sorted()
return IntRange(1, sortedCards.size).zip(sortedCards).sumOf { (rank, card) -> rank * card.bid * 1L }
}
fun part2(input: List<String>): Long {
val sortedCards = input.map { parseCameCard(it, isJokerRule = true) }.sorted()
return IntRange(1, sortedCards.size).zip(sortedCards).sumOf { (rank, card) -> rank * card.bid * 1L }
}
private fun parseCameCard(camelCard: String, isJokerRule: Boolean): CamelCard {
val (card, bid) = camelCard.split(' ')
return CamelCard(card, bid.toInt(), isJokerRule)
}
enum class CombinationType(val priority: Int) {
HIGH_CARD(1),
ONE_PAIR(2),
TWO_PAIR(3),
THREE_OF_A_KIND(4),
FULL_HOUSE(5),
FOUR_OF_A_KIND(6),
FIVE_OF_A_KIND(7),
}
data class CamelCard(val card: String, val bid: Int, val isJokerRule: Boolean = false) : Comparable<CamelCard> {
private val numbers = convertToNumbers(card, isJokerRule)
private val type = if (isJokerRule) getTypeWithJoker(card) else getType(card)
override fun compareTo(other: CamelCard): Int {
if (type.priority < other.type.priority) return -1
if (type.priority > other.type.priority) return 1
for ((thisNum, otherNum) in numbers.zip(other.numbers)) {
if (thisNum < otherNum) return -1
if (thisNum > otherNum) return 1
}
return 0
}
private companion object {
fun convertToNumbers(card: String, isJokerRule: Boolean): List<Int> = card.toCharArray()
.map { num ->
when (num) {
'T' -> 10
'J' -> if (isJokerRule) 1 else 11
'Q' -> 12
'K' -> 13
'A' -> 14
else -> num.digitToInt()
}
}
fun getType(card: String): CombinationType {
val counts = card.groupingBy { it }.eachCount().values
return calculateType(counts)
}
fun getTypeWithJoker(card: String): CombinationType {
val counts = card.groupingBy { it }.eachCount()
val jokerCounts = counts.getOrDefault('J', 0)
if (jokerCounts == 0) return getType(card)
if (jokerCounts == 5) return CombinationType.FIVE_OF_A_KIND
val otherCounts = counts.filterKeys { it != 'J' }.values
val type = calculateType(otherCounts)
return if (type == CombinationType.FOUR_OF_A_KIND) CombinationType.FIVE_OF_A_KIND
else if (type == CombinationType.THREE_OF_A_KIND && jokerCounts == 2) CombinationType.FIVE_OF_A_KIND
else if (type == CombinationType.THREE_OF_A_KIND) CombinationType.FOUR_OF_A_KIND
else if (type == CombinationType.TWO_PAIR) CombinationType.FULL_HOUSE
else if (type == CombinationType.ONE_PAIR && jokerCounts == 3) CombinationType.FIVE_OF_A_KIND
else if (type == CombinationType.ONE_PAIR && jokerCounts == 2) CombinationType.FOUR_OF_A_KIND
else if (type == CombinationType.ONE_PAIR) CombinationType.THREE_OF_A_KIND
else if (jokerCounts == 4) CombinationType.FIVE_OF_A_KIND
else if (jokerCounts == 3) CombinationType.FOUR_OF_A_KIND
else if (jokerCounts == 2) CombinationType.THREE_OF_A_KIND
else CombinationType.ONE_PAIR
}
private fun calculateType(counts: Collection<Int>): CombinationType =
if (counts.contains(5)) CombinationType.FIVE_OF_A_KIND
else if (counts.contains(4)) CombinationType.FOUR_OF_A_KIND
else if (counts.contains(2) && counts.contains(3)) CombinationType.FULL_HOUSE
else if (counts.contains(3)) CombinationType.THREE_OF_A_KIND
else if (counts.count { it == 2 } == 2) CombinationType.TWO_PAIR
else if (counts.contains(2)) CombinationType.ONE_PAIR
else CombinationType.HIGH_CARD
}
}
}
fun main() {
val day07 = Day07()
val input = readInputAsStringList("day07.txt")
println("07, part 1: ${day07.part1(input)}")
println("07, part 2: ${day07.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 4,542 | advent-of-code-2023 | MIT License |
src/y2021/Day13.kt | Yg0R2 | 433,731,745 | false | null | package y2021
fun main() {
fun part1(input: List<String>): Int {
// y (column) to x (row)
val coordinates: List<Pair<Int, Int>> = input.getCoordinates()
// y => horizontal (row)
// x => vertical (column)
val folds: List<Pair<String, Int>> = input.getFoldAlongs()
return coordinates
.fold(mutableListOf()) { acc: MutableList<Pair<Int, Int>>, coordinate: Pair<Int, Int> ->
acc.add(foldCoordinate(coordinate, folds[0]))
acc
}
.filter { it.first >= 0 && it.second >= 0 }
.toSet()
.count()
}
fun part2(input: List<String>): String {
// y (column) to x (row)
val coordinates: List<Pair<Int, Int>> = input.getCoordinates()
// y => horizontal (row)
// x => vertical (column)
val folds: List<Pair<String, Int>> = input.getFoldAlongs()
val foldedResult: List<Pair<Int, Int>> = folds
.fold(coordinates.toMutableList()) { newCoordinates: MutableList<Pair<Int, Int>>, foldCoordinate: Pair<String, Int> ->
newCoordinates.fold(mutableListOf()) { acc: MutableList<Pair<Int, Int>>, coordinate: Pair<Int, Int> ->
acc.add(foldCoordinate(coordinate, foldCoordinate))
acc
}
}
val maxColumn = foldedResult.maxOf { it.first }
val maxRow = foldedResult.maxOf { it.second }
return foldedResult
.fold(MutableList(maxRow + 1) { MutableList(maxColumn + 1) { " " } }) { acc: MutableList<MutableList<String?>>, pair: Pair<Int, Int> ->
acc[pair.second][pair.first] = "#"
acc
}
.joinToString("\n") { it.joinToString("") }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput).also { println(it) } == 17)
check(part2(testInput).also { println(it) } == "#####\n# #\n# #\n# #\n#####")
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private fun List<String>.getCoordinates(): List<Pair<Int, Int>> =
this.filter { !it.startsWith("fold along") }
.filter { it.isNotBlank() }
.map { it.split(",") }
.map { it[0].toInt() to it[1] .toInt()}
private fun List<String>.getFoldAlongs(): List<Pair<String, Int>> =
this.filter { it.startsWith("fold along") }
.map { it.replace("fold along", "").trim() }
.map { it.split("=") }
.map { it[0] to it[1].toInt() }
private fun foldCoordinate(coordinate: Pair<Int, Int>, foldCoordinate: Pair<String, Int>): Pair<Int, Int> =
if (foldCoordinate.first == "x") {
val foldX = foldCoordinate.second
if (coordinate.first < (foldX)) {
coordinate
}
else {
((2 * foldX) - coordinate.first) to coordinate.second
}
}
else {
val foldY = foldCoordinate.second
if (coordinate.second < foldY) {
coordinate
}
else {
coordinate.first to ((2 * foldY) - coordinate.second)
}
}
| 0 | Kotlin | 0 | 0 | d88df7529665b65617334d84b87762bd3ead1323 | 3,206 | advent-of-code | Apache License 2.0 |
src/Day09.kt | Reivax47 | 572,984,467 | false | {"Kotlin": 32685} | import kotlin.math.abs
import kotlin.math.sqrt
import kotlin.math.pow
fun main() {
fun euclidienne(xH: Int, yH: Int, xT: Int, yT: Int): Float {
return sqrt((xH - xT).toFloat().pow(2) + (yH - yT).toFloat().pow(2))
}
fun solution(input: List<String>, nombreDeNoeuds: Int): Int {
val liste = mutableSetOf<positionOccupee>()
val posx = Array(nombreDeNoeuds) { 0 }
val posy = Array(nombreDeNoeuds) { 0 }
liste.add(positionOccupee(posx[nombreDeNoeuds - 1], posy[nombreDeNoeuds - 1]))
input.forEach { ligne ->
val direction = ligne.substring(0, 1)
val combien = ligne.substring(2).toInt()
for (i in 1..combien) {
when (direction) {
"R" -> posx[0]++
"L" -> posx[0]--
"U" -> posy[0]++
"D" -> posy[0]--
}
for (j in 1 until nombreDeNoeuds) {
val distance = euclidienne(posx[j - 1], posy[j - 1], posx[j], posy[j])
if (distance > 2) {
// diagonale
posy[j] += if (posy[j - 1] > posy[j]) 1 else -1
posx[j] += if (posx[j - 1] > posx[j]) 1 else -1
} else if (abs(posx[j - 1] - posx[j]) > 1) {
// Sur le meme Y.
posx[j] += if (posx[j - 1] > posx[j]) 1 else -1
} else if (abs((posy[j] - posy[j - 1])) > 1) {
// Sur le meme X
posy[j] += if (posy[j - 1] > posy[j]) 1 else -1
}
}
liste.add(positionOccupee(posx[nombreDeNoeuds - 1], posy[nombreDeNoeuds - 1]))
}
}
return liste.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(solution(testInput, 2) == 13)
check(solution(testInput, 10) == 1)
val testInputBis = readInput("Day09_testbis")
check(solution(testInputBis, 10) == 36)
val input = readInput("Day09")
println(solution(input, 2))
println(solution(input, 10))
}
data class positionOccupee(val x: Int, val y: Int) | 0 | Kotlin | 0 | 0 | 0affd02997046d72f15d493a148f99f58f3b2fb9 | 2,277 | AD2022-01 | Apache License 2.0 |
src/Day17.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | fun main() {
data class Point(var x: Int, var y: Int)
class Rock(val lines: List<String>) {
val width = lines[0].length
val height = lines.size
fun canPush(field: Array<CharArray>, pos: Point, moveX: Int) = !willIntersect(field, pos, moveX, 0)
fun canFall(field: Array<CharArray>, pos: Point) = !willIntersect(field, pos, 0, -1)
fun willIntersect(field: Array<CharArray>, pos: Point, dx: Int, dy: Int): Boolean {
val newX = pos.x + dx
val newY = pos.y + dy
if (newX < 0 || newX + width > 7) return true
for (y in lines.indices) {
for (x in 0 until width) {
if (lines[height - y - 1][x] == '#' && field[x + newX][y + newY] == '#') {
return true
}
}
}
return false
}
fun append(top: Array<CharArray>, pos: Point) {
for (y in lines.indices) {
for (x in 0 until width) {
if (lines[height - y - 1][x] == '#') {
top[x + pos.x][y + pos.y] = '#'
}
}
}
}
}
fun solve(patterns: String, count: Long): Long {
val rocks = readInput("Day17_rocks")
.split("\n\n")
.map { Rock(it.lines()) }
val field = Array(7) { CharArray(5000) { if (it == 0) '#' else '.' } }
var rock = 0
var pattern = 0
fun drop(rock: Rock) {
val pos = Point(2, field.maxOf { it.lastIndexOf('#') } + 4)
while (true) {
val move = if (patterns[pattern] == '>') 1 else -1
pattern = (pattern + 1) % patterns.length
if (rock.canPush(field, pos, move)) {
pos.x += move
}
if (rock.canFall(field, pos)) {
pos.y--
} else {
rock.append(field, pos)
return
}
}
}
class State(val pattern: String, val rocks: Int, val height: Int)
val prevPattern = HashMap<Pair<Int, Int>, State>()
val maxHeights = mutableListOf<Int>()
repeat(2000) { rocksCounter ->
drop(rocks[rock])
rock = (rock + 1) % rocks.size
val maxHeight = field.maxOf { it.lastIndexOf('#') }
maxHeights += maxHeight
val curPattern = field.map { it[maxHeight] }.toString()
val last = prevPattern[rock to pattern]
if (last != null && last.pattern == curPattern) {
println("Found pattern = $curPattern")
println("Height diff = ${maxHeight - last.height}, rocks diff = ${rocksCounter - last.rocks}")
val heightDiff = maxHeight - last.height
val cycle = rocksCounter - last.rocks
val remainsFromLast = count - 1 - last.rocks
val cycles = remainsFromLast / cycle
val fromLastCycle = (remainsFromLast % cycle).toInt()
return cycles * heightDiff + maxHeights[last.rocks + fromLastCycle]
}
prevPattern[rock to pattern] = State(curPattern, rocksCounter, maxHeight)
}
return -1
}
fun part1(patterns: String) = solve(patterns, 2022).toInt()
fun part2(patterns: String) = solve(patterns, 1000000000000L)
val testInput = readInput("Day17_test")
check(part1(testInput), 3068)
check(part2(testInput), 1514285714288L)
val input = readInput("Day17")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 3,682 | Advent-of-Code-2022 | Apache License 2.0 |
src/day17/Code.kt | fcolasuonno | 572,734,674 | false | {"Kotlin": 63451, "Dockerfile": 1340} | package day17
import Coord
import day06.main
import readInput
import java.util.*
fun main() {
fun Set<Coord>.moveRight() = buildSet { this@moveRight.forEach { add(it.copy(first = it.first + 1)) } }
fun Set<Coord>.moveLeft() = buildSet { this@moveLeft.forEach { add(it.copy(first = it.first - 1)) } }
fun Set<Coord>.moveDown() = buildSet { this@moveDown.forEach { add(it.copy(second = it.second - 1)) } }
fun Set<Coord>.moveUp(amount: Int) = buildSet { this@moveUp.forEach { add(it.copy(second = it.second + amount)) } }
val rockTypes = listOf(
//-
(0..3).map { Coord(2 + it, 3) },
//+
((0..2).map { Coord(2 + it, 4) } + Coord(3, 3) + Coord(3, 5)),
//L
((0..2).map { Coord(2 + it, 3) } + Coord(4, 4) + Coord(4, 5)),
//|
(0..3).map { Coord(2, 3 + it) },
// #
((0..1).map { Coord(2 + it, 3) } + (0..1).map { Coord(2 + it, 4) })
).map { it.toSet() }
data class Simulation(val input: String) {
val chamber = TreeSet(compareBy(Coord::second, Coord::first))
val rockSequence = generateSequence(0) { it + 1 }.map { rockTypes[it % rockTypes.size] }.iterator()
val directions = generateSequence(0) { it + 1 }.map {
if (input[it % input.length] == '>') Set<Coord>::moveRight else Set<Coord>::moveLeft
}.iterator()
fun checkCollision(rock: Set<Coord>) = rock.takeIf {
it.intersect(chamber).isEmpty() && it.all { (rockX, rockY) -> rockY >= 0 && rockX in 0..6 }
}
val topRow
get() = chamber.lastOrNull()?.let { it.second + 1 } ?: 0
fun simulate() = generateSequence {
generateSequence(rockSequence.next().moveUp(topRow) to true) { (currentRock, sideStep) ->
if (sideStep) {
checkCollision(directions.next()(currentRock)) ?: currentRock
} else {
checkCollision(currentRock.moveDown())
}?.let { it to !sideStep }
}.last().let { (rocks, _) ->
chamber.addAll(rocks)
}
chamber.last().second + 1
}
}
fun part1(input: String, times: Int) = Simulation(input).simulate().take(times).last()
fun part2(input: String, times: Long) = Simulation(input).simulate().take(4000).toList().let { height ->
(1..height.size).first {
val lastWindow = height.takeLast(500)
val previousWindow = height.dropLast(it).takeLast(500)
lastWindow.zip(previousWindow, Int::minus).distinct().size == 1
}.let { modulo ->
val repetitions = (times - height.size) / modulo + 1
val index = (times - 1 - (repetitions * modulo)).toInt()
val step = height[index] - height[index - modulo]
height[index] + repetitions * step
}
}
val input = readInput(::main.javaClass.packageName)
println("Part1=\n" + part1(input.first(), 2022))
println("Part2=\n" + part2(input.first(), 1000000000000L))
} | 0 | Kotlin | 0 | 0 | 9cb653bd6a5abb214a9310f7cac3d0a5a478a71a | 3,046 | AOC2022 | Apache License 2.0 |
src/main/kotlin/day12/CaveExpedition.kt | Arch-vile | 433,381,878 | false | {"Kotlin": 57129} | package day12
import utils.read
fun main() {
solve()
.let { println(it) }
}
data class Cave(var accessTo: MutableList<Cave>, val name: String) {
fun isSmall(): Boolean {
if(isEnd() || isStart())
return false;
return """[a-z]*""".toRegex().matches(name)
}
private fun isEnd(): Boolean = name == "end"
private fun isStart() = name == "start"
fun addAccessTo(other: Cave) {
// Do not add route to back to Start and no routes out of End
if (!other.isStart() && !isEnd()) {
accessTo.add(other)
}
}
override fun toString(): String {
return name
}
override fun equals(other: Any?): Boolean {
return if(other is Cave)
name == other.name
else
false
}
}
fun solve(): List<Int> {
val caves = mutableMapOf<String, Cave>()
read("./src/main/resources/day12Input.txt")
.map { it.split("-") }
.forEach {
val source = caves.getOrDefault(it[0], Cave(mutableListOf(), it[0]))
val target = caves.getOrDefault(it[1], Cave(mutableListOf(), it[1]))
source.addAccessTo(target)
target.addAccessTo(source)
caves.put(source.name, source)
caves.put(target.name, target)
}
return listOf(
countRoutes(false, caves["start"]!!, caves["end"]!!),
countRoutes(true, caves["start"]!!, caves["end"]!!))
}
fun countRoutes(allowDuplicates: Boolean, start: Cave, end: Cave): Int {
val routes = findRoutes(allowDuplicates, listOf(),start)
val routesReachingEnd = routes.filter { it.contains(end) }
return routesReachingEnd.count()
}
fun findRoutes(allowDuplicates: Boolean, path: List<Cave>, cave: Cave): MutableList<MutableList<Cave>> {
if (cave.accessTo.isEmpty()) {
return mutableListOf(mutableListOf(cave))
}
val newPath = path.plus(cave)
val childRoutes = cave.accessTo
.filter {
if(it.isSmall()) {
if(newPath.contains(it))
allowDuplicates && !hasDoubleSmall(newPath)
else
true
} else true
}
.flatMap {
findRoutes(allowDuplicates, newPath, it)
}
childRoutes.forEach { it.add(0, cave) }
return childRoutes.toMutableList()
}
fun hasDoubleSmall(newPath: List<Cave>): Boolean {
return newPath
.filter { it.isSmall() }
.map { it.name }
.distinct().count() != newPath.filter { it.isSmall() }.count()
}
| 0 | Kotlin | 0 | 0 | 4cdafaa524a863e28067beb668a3f3e06edcef96 | 2,570 | adventOfCode2021 | Apache License 2.0 |
src/main/kotlin/day4.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | private val testInput1 =
"""
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
22 13 17 11 0
8 2 23 4 24
21 9 14 16 7
6 10 3 18 5
1 12 20 15 19
3 15 0 2 22
9 18 13 17 5
19 8 7 25 23
20 11 10 24 4
14 21 16 12 6
14 21 17 24 4
10 16 15 9 19
18 8 23 26 20
22 11 13 6 5
2 0 12 3 7
""".trimIndent()
fun main() {
//val input = testInput1
val input = readInputFile("input4")
val s = input.splitByEmptyLine()
val numbers = s[0].split(",").map { it.toInt() }
val boardsString = s.drop(1)
println("part1: ${part1(boardsString, numbers)}")
println("part2: ${part2(boardsString, numbers)}")
println("day4")
}
private fun part2(boardsString: List<String>, numbers: List<Int>): Int {
val boards = boardsString.map { parseBoard(it.lines()) }
var index = -1
while (boards.count { !it.isWinning() } > 1) {
index++
val number = numbers[index]
playRound(boards, number)
}
val loosingBoard = boards.first { !it.isWinning() }
while (!loosingBoard.isWinning()) {
index++
val number = numbers[index]
loosingBoard.mark(number)
}
return loosingBoard.sumUnmarked() * numbers[index]
}
private fun part1(boardsString: List<String>, numbers: List<Int>): Int {
val boards = boardsString.map { parseBoard(it.lines()) }
var index = -1
while (!boards.any { it.isWinning() }) {
index++
val number = numbers[index]
playRound(boards, number)
}
val winningBoard = boards.first { it.isWinning() }
println(winningBoard.sumUnmarked())
println(numbers[index])
return winningBoard.sumUnmarked() * numbers[index]
}
private fun playRound(boards: List<BingoBoard>, number: Int) {
boards.forEach { board -> board.mark(number) }
}
private fun parseBoard(string: List<String>): BingoBoard = BingoBoard(
string.map { row ->
row
// some rows start with spaces to indent single digit numbers
.removePrefix(" ")
// amount of spaces varies to indent single digit numbers.
.split(Regex(" +"))
.map { it.toInt() }
})
// mutable!
private class BingoBoard(val numbers: List<List<Int>>) {
init {
// no duplicates
require(numbers.flatten().size == numbers.flatten().toSet().size)
}
private val height = numbers.size
private val width = numbers.first().size
private val marked = mutableMapOf<Pair<Int, Int>, Boolean>().apply {
(0 until height).forEach { row ->
(0 until width).forEach { col ->
put(row to col, false)
}
}
}
override fun toString(): String {
return numbers.mapIndexed { r, row ->
row.mapIndexed { c, value ->
if (marked[r to c] == true) "X" else value.toString()
}.joinToString(" ")
}.joinToString("\n")
}
fun mark(number: Int) {
val index = indexOf(number) ?: return
marked[index] = true
}
private fun indexOf(number: Int): Pair<Int, Int>? {
val row = numbers.indexOfFirst { number in it }
if (row == -1) return null
val col = numbers[row].indexOf(number)
if (col == -1) return null
return row to col
}
fun isWinning(): Boolean {
val winningRow = (0 until height).any { row ->
(0 until width).map { row to it }.all { marked[it] == true }
}
if (winningRow) return true
val winningCol = (0 until width).any { col ->
(0 until height).map { it to col }.all { marked[it] == true }
}
return winningCol
}
fun sumUnmarked(): Int {
var sum = 0
(0 until height).forEach { row ->
(0 until width).forEach { col ->
if (!marked[row to col]!!) {
sum += numbers[row][col]
}
}
}
return sum
}
}
| 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 3,984 | AOC-2021 | MIT License |
src/main/kotlin/solutions/day14/Day14.kt | Dr-Horv | 570,666,285 | false | {"Kotlin": 115643} | package solutions.day14
import solutions.Solver
import utils.Coordinate
import utils.Direction
import utils.step
import java.lang.Integer.max
import java.lang.Integer.min
enum class CaveState {
SAND,
AIR,
ROCK;
override fun toString(): String {
return when (this) {
SAND -> "o"
AIR -> "."
ROCK -> "#"
}
}
}
class Day14 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
var map = mutableMapOf<Coordinate, CaveState>().withDefault { CaveState.AIR }
for (line in input) {
val coordinates = line.split("->")
.map { parseCoordinate(it) }
coordinates.windowed(2).forEach {
val xs = min(it[0].x, it[1].x)..max(it[0].x, it[1].x)
val ys = min(it[0].y, it[1].y)..max(it[0].y, it[1].y)
for (x in xs) {
for (y in ys) {
map[Coordinate(x, y)] = CaveState.ROCK
}
}
}
}
val abyssLine = map.keys.maxBy { it.y }.y
map = if (partTwo) {
map.withDefault {
when (it.y) {
abyssLine + 2 -> CaveState.ROCK
else -> CaveState.AIR
}
}
} else {
map
}
val updatedAbyssLine = if (partTwo) {
abyssLine + 5
} else {
abyssLine
}
while (true) {
val sandsBefore = map.values.count { it == CaveState.SAND }
dropSand(map, updatedAbyssLine)
val sandsAfter = map.values.count { it == CaveState.SAND }
if ((sandsBefore == sandsAfter) || (map.getValue(Coordinate(500, 0)) == CaveState.SAND)) {
return sandsAfter.toString()
}
}
}
private fun dropSand(map: MutableMap<Coordinate, CaveState>, abyssline: Int) {
var sand = Coordinate(500, 0)
var isMoving = true
while (isMoving && sand.y < abyssline) {
val newPos = listOf(
sand.step(Direction.UP),
sand.step(Direction.UP).step(Direction.LEFT),
sand.step(Direction.UP).step(Direction.RIGHT)
).find { map.getValue(it) == CaveState.AIR }
if (newPos != null) {
sand = newPos
} else {
map[sand] = CaveState.SAND
isMoving = false
}
}
}
private fun parseCoordinate(s: String): Coordinate {
val parts = s.split(",")
.map { it.trim() }
.map { it.toInt() }
return Coordinate(x = parts[0], y = parts[1])
}
}
| 0 | Kotlin | 0 | 2 | 6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e | 2,755 | Advent-of-Code-2022 | MIT License |
2021/src/main/kotlin/day20_fast.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.IntGrid
import utils.MutableIntGrid
import utils.Parser
import utils.Solution
fun main() {
Day20Fast.run()
}
object Day20All {
@JvmStatic fun main(args: Array<String>) {
mapOf("func" to Day20Func, "fast" to Day20Fast).forEach { (header, solution) ->
solution.run(header = header, skipPart1 = false, skipTest = false, printParseTime = true)
}
}
}
object Day20Fast : Solution<Pair<IntGrid, List<Int>>>() {
override val name = "day20"
override val parser = Parser { input ->
val (lookupString, imageString) = input.split("\n\n", limit = 2)
val lookup = lookupString.replace("\n", "").trim().map { if (it == '#') 1 else 0 }
val gridLines = imageString.split("\n").map { it.trim() }.filter { it.isNotBlank() }
val gridW = gridLines.first().length
val gridH = gridLines.size
val grid = IntGrid(gridW, gridH) { (x, y) -> if (gridLines[y][x] == '#') 1 else 0 }
return@Parser grid to lookup
}
fun enhance(input: IntGrid, output: MutableIntGrid, lookup: List<Int>) {
val padding = lookup[if (input[0][0] == 0) 0 else 511]
val width = input.width
val height = input.height
for (x in 0 until width) {
output[x][0] = padding
output[x][height - 1] = padding
}
for (y in 0 until height) {
output[0][y] = padding
output[width - 1][y] = padding
}
for (x in 1 until width - 1) {
for (y in 1 until height - 1) {
val outIndex =
(input[x-1][y-1] shl 8) or
(input[x][y-1] shl 7) or
(input[x+1][y-1] shl 6) or
(input[x-1][y] shl 5) or
(input[x][y] shl 4) or
(input[x+1][y] shl 3) or
(input[x-1][y+1] shl 2) or
(input[x][y+1] shl 1) or
(input[x+1][y+1])
output[x][y] = lookup[outIndex]
}
}
}
override fun part1(input: Pair<IntGrid, List<Int>>): Int {
val output = solve(input, 2)
return output.values.count { it != 0 }
}
override fun part2(input: Pair<IntGrid, List<Int>>): Int {
val output = solve(input, 50)
return output.values.count { it != 0 }
}
private fun solve(input: Pair<IntGrid, List<Int>>, days: Int): MutableIntGrid {
val b1 = input.first.borderWith(0, days + 1).toMutable()
val w = b1.width
val h = b1.height
val b2 = IntGrid(w, h) { 0 }.toMutable()
repeat(days) { day ->
if (day % 2 == 0) {
enhance(b1, b2, input.second)
} else {
enhance(b2, b1, input.second)
}
}
return if (days % 2 == 0) b1 else b2
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,553 | aoc_kotlin | MIT License |
src/day13/Day13.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day13
import readInput
const val day = "13"
fun main() {
fun calculatePart1Score(input: List<String>): Int {
val packetGroups = input
.map { it.parsePackets() }
.windowed(2, step = 3)
val valid = packetGroups
.map { (left, right) -> left.isValid(right) }
return valid.withIndex().filter { it.value == ThreeState.VALID }.sumOf { it.index + 1 }
}
fun calculatePart2Score(input: List<String>): Int {
val divider1 = "[[2]]".parsePackets()
val divider2 = "[[6]]".parsePackets()
val allPackets = listOf(divider1, divider2) + input
.filter { it.isNotBlank() }
.map { it.parsePackets() }
val sorted = allPackets.sortedWith(Comparator { o1, o2 ->
val valid = o1.isValid(o2)
when (valid) {
ThreeState.INVALID -> 1
ThreeState.UNDECIDED -> 0
ThreeState.VALID -> -1
}
})
val (divIdx1, divIdx2) = sorted.withIndex().filter { it.value == divider1 || it.value == divider2 }
return (divIdx1.index + 1) * (divIdx2.index + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
val part1points = calculatePart1Score(input)
println("Part1 test points: $part1TestPoints")
println("Part1 points: $part1points")
check(part1TestPoints == 13)
val part2TestPoints = calculatePart2Score(testInput)
val part2points = calculatePart2Score(input)
println("Part2 test points: \n$part2TestPoints")
println("Part2 points: \n$part2points")
check(part2TestPoints == 140)
}
fun String.parsePackets(): ListPacket {
val topLevel = ListPacket(mutableListOf(), null)
var currentList = topLevel
var stringBuffer = ""
this.toCharArray().drop(1).dropLast(1).forEach { char ->
when (char) {
'[' -> {
val newList = ListPacket(mutableListOf(), currentList)
currentList.list.add(newList)
currentList = newList
}
']' -> {
if (stringBuffer.isNotEmpty()) {
currentList.list.add(IntPacket(stringBuffer.toInt(), currentList))
stringBuffer = ""
}
currentList = currentList.parent ?: error("parent null")
}
',' -> {
if (stringBuffer.isNotEmpty()) {
currentList.list.add(IntPacket(stringBuffer.toInt(), currentList))
stringBuffer = ""
}
}
else -> stringBuffer += char
}
}
if (stringBuffer.isNotEmpty()) {
currentList.list.add(IntPacket(stringBuffer.toInt(), currentList))
stringBuffer = ""
}
return topLevel
}
sealed interface Packet {
val parent: ListPacket?
fun isValid(right: Packet): ThreeState
}
data class ListPacket(val list: MutableList<Packet>, override val parent: ListPacket?) : Packet {
override fun toString(): String {
return "ListPacket(list=$list)"
}
override fun isValid(right: Packet): ThreeState {
return when (right) {
is ListPacket -> this.list.withIndex().map { (idx, leftChild) ->
if (idx > right.list.lastIndex) {
return@map ThreeState.INVALID
}
return@map leftChild.isValid(right.list[idx])
}.firstOrNull { it != ThreeState.UNDECIDED }
?: if (this.list.size < right.list.size) ThreeState.VALID else ThreeState.UNDECIDED
is IntPacket -> isValid(ListPacket(mutableListOf(right), right.parent))
}
}
}
data class IntPacket(val value: Int, override val parent: ListPacket?) : Packet {
override fun toString(): String {
return "IntPacket(value=$value)"
}
override fun isValid(right: Packet): ThreeState {
return when (right) {
is ListPacket -> ListPacket(mutableListOf(this), this.parent).isValid(right)
is IntPacket ->
when {
this.value < right.value -> ThreeState.VALID
this.value > right.value -> ThreeState.INVALID
else -> ThreeState.UNDECIDED
}
}
}
}
enum class ThreeState {
VALID,
INVALID,
UNDECIDED
} | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 4,571 | advent-of-code-22-kotlin | Apache License 2.0 |
2019/src/main/kotlin/day3.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Segment
import utils.Solution
import utils.Vec2i
import utils.mapItems
import utils.times
private typealias D3Input = Pair<List<Vec2i>, List<Vec2i>>
fun main() {
Day3.run(skipTest = false)
}
object Day3 : Solution<D3Input>() {
override val name = "day3"
override val parser = Parser.lines.mapItems { line ->
line.split(",").map {
val direction = it.first()
val distance = it.substring(1).toInt()
when (direction) {
'U' -> Vec2i(0, distance)
'D' -> Vec2i(0, -distance)
'L' -> Vec2i(-distance, 0)
'R' -> Vec2i(distance, 0)
else -> throw IllegalArgumentException("Unknown direction $direction")
}
}
}.map { it[0] to it[1] }
private fun intersectionsWithSteps(input: D3Input): List<Pair<Vec2i, Int>> {
val s1 = mutableListOf<Pair<Segment, Int>>()
val s2 = mutableListOf<Pair<Segment, Int>>()
var origin = Vec2i(0, 0)
var steps = 0
input.first.forEach {
s1 += Segment(origin, origin + it) to steps
origin += it
steps += it.manhattanDistanceTo(Vec2i(0, 0))
}
origin = Vec2i(0, 0)
steps = 0
input.second.forEach {
s2 += Segment(origin, origin + it) to steps
origin += it
steps += it.manhattanDistanceTo(Vec2i(0, 0))
}
return (s1 * s2).mapNotNull { (a, b) ->
val p = (a.first.points.toSet() intersect b.first.points.toSet()).firstOrNull()
if (p == null) { null } else {
p to a.second + (p.manhattanDistanceTo(a.first.start)) + b.second + (p.manhattanDistanceTo(b.first.start))
}
}
.filter { it.first != Vec2i(0, 0) }
}
override fun part1(input: D3Input): Int {
return intersectionsWithSteps(input)
.minOf { (pt, _) -> pt.manhattanDistanceTo(Vec2i(0, 0)) }
}
override fun part2(input: D3Input): Int {
return intersectionsWithSteps(input)
.minOf { (_, steps) -> steps }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,945 | aoc_kotlin | MIT License |
src/day08/Day08.kt | jacobprudhomme | 573,057,457 | false | {"Kotlin": 29699} | import java.io.File
class Matrix<T>(private val mtx: List<List<T>>) {
fun dimensions(): Pair<Int, Int> = Pair(mtx.size, mtx[0].size)
fun getRow(rowIdx: Int): List<T> = mtx[rowIdx]
fun getColumn(colIdx: Int): List<T> = mtx.map { row -> row[colIdx] }
fun forEachIndexed(f: (rowIndex: Int, columnIndex: Int, T) -> Unit) {
this.mtx.forEachIndexed { rowIndex, row ->
row.forEachIndexed { columnIndex, item ->
f(rowIndex, columnIndex, item)
}
}
}
}
fun main() {
fun readInput(name: String) = File("src/day08", name)
.readLines()
fun smallerToLeft(mtx: Matrix<Int>, thisTree: Int, pos: Pair<Int, Int>): Int {
val row = mtx.getRow(pos.first).subList(0, pos.second)
return row.takeLastWhile { tree -> tree < thisTree }.count()
}
fun smallerToRight(mtx: Matrix<Int>, thisTree: Int, pos: Pair<Int, Int>): Int {
val row = mtx.getRow(pos.first).subList(pos.second + 1, mtx.dimensions().second)
return row.takeWhile { tree -> tree < thisTree }.count()
}
fun smallerAbove(mtx: Matrix<Int>, thisTree: Int, pos: Pair<Int, Int>): Int {
val col = mtx.getColumn(pos.second).subList(0, pos.first)
return col.takeLastWhile { tree -> tree < thisTree }.count()
}
fun smallerBelow(mtx: Matrix<Int>, thisTree: Int, pos: Pair<Int, Int>): Int {
val col = mtx.getColumn(pos.second).subList(pos.first + 1, mtx.dimensions().first)
return col.takeWhile { tree -> tree < thisTree }.count()
}
fun isVisibleFromADirection(mtx: Matrix<Int>, tree: Int, pos: Pair<Int, Int>): Boolean {
val (height, width) = mtx.dimensions()
return ((smallerToLeft(mtx, tree, pos) == pos.second)
or (smallerToRight(mtx, tree, pos) == width - pos.second - 1)
or (smallerAbove(mtx, tree, pos) == pos.first)
or (smallerBelow(mtx, tree, pos) == height - pos.first - 1))
}
fun calculateVisibilityScore(mtx: Matrix<Int>, tree: Int, pos: Pair<Int, Int>): Int {
val (row, col) = pos
val (height, width) = mtx.dimensions()
var stl = smallerToLeft(mtx, tree, pos)
if (stl < col) { ++stl }
var str = smallerToRight(mtx, tree, pos)
if (str < width - col - 1) { ++str }
var sa = smallerAbove(mtx, tree, pos)
if (sa < row) { ++sa }
var sb = smallerBelow(mtx, tree, pos)
if (sb < height - row - 1) { ++sb }
return (stl * str * sa * sb)
}
fun part1(input: List<String>): Int {
val grid = Matrix(input.map { row -> row.map(Char::digitToInt) })
val treesSeen = mutableSetOf<Pair<Int, Int>>()
var count = 0
grid.forEachIndexed { rowIdx, colIdx, tree ->
if ((Pair(rowIdx, colIdx) !in treesSeen) and isVisibleFromADirection(grid, tree, Pair(rowIdx, colIdx))) {
count += 1
treesSeen.add(Pair(rowIdx, colIdx))
}
}
return count
}
fun part2(input: List<String>): Int {
val grid = Matrix(input.map { row -> row.map(Char::digitToInt) })
val treesSeen = mutableSetOf<Pair<Int, Int>>()
var maxScoreSeenSoFar = 0
grid.forEachIndexed { rowIdx, colIdx, tree ->
if (Pair(rowIdx, colIdx) !in treesSeen) {
val visibilityScore = calculateVisibilityScore(grid, tree, Pair(rowIdx, colIdx))
if (visibilityScore > maxScoreSeenSoFar) {
maxScoreSeenSoFar = visibilityScore
}
treesSeen.add(Pair(rowIdx, colIdx))
}
}
return maxScoreSeenSoFar
}
val input = readInput("input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 9c2b080aea8b069d2796d58bcfc90ce4651c215b | 3,786 | advent-of-code-2022 | Apache License 2.0 |
src/day13/Day13.kt | iulianpopescu | 572,832,973 | false | {"Kotlin": 30777} | package day13
import readFile
private const val DAY = "13"
private const val DAY_TEST = "day${DAY}/Day${DAY}_test"
private const val DAY_INPUT = "day${DAY}/Day${DAY}"
fun main() {
fun parseInput(input: String): List<Pair<Node, Node>> {
val lists = input.split("\n\n")
val pairs = lists.map {
val (first, second) = it.split('\n')
first.let {
index = 0
parseItem(first)
} to second.let {
index = 0
parseItem(second)
}
}
return pairs
}
fun part1(input: String) = parseInput(input).foldIndexed(0) { index, total, (first, second) ->
if (first.compareTo(second) <= 0) total + index + 1 else total
}
fun part2(input: String) = parseInput(input).flatMap {
listOf(it.first, it.second)
}.let {
it + Node.doubleNode(2) + Node.doubleNode(6)
}.sortedWith { t1, t2 ->
t1.compareTo(t2)
}.foldIndexed(1) { index, total, item ->
val factor = if (item == Node.doubleNode(2) || item == Node.doubleNode(6)) index + 1 else 1
total * factor
}
// test if implementation meets criteria from the description, like:
val testInput = readFile(DAY_TEST)
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readFile(DAY_INPUT)
println(part1(input)) // 5198
println(part2(input)) // 22344
}
private sealed class Node {
data class Item(val value: Int) : Node()
data class Sublist(val list: List<Node>) : Node()
fun compareTo(other: Node): Int = when {
this is Item && other is Item -> this.value.compareTo(other.value)
this is Item && other is Sublist -> Sublist(listOf(this)).compareTo(other)
this is Sublist && other is Item -> this.compareTo(Sublist(listOf(other)))
else -> {
val thisList = (this as Sublist).list
val otherList = (other as Sublist).list
var comparison: Int? = null
for (i in 0..minOf(thisList.lastIndex, otherList.lastIndex)) {
val itemComparison = thisList[i].compareTo(otherList[i])
if (itemComparison == 0)
continue
comparison = itemComparison
break
}
comparison ?: this.list.size.compareTo(other.list.size)
}
}
companion object {
fun doubleNode(value: Int) = Sublist(listOf(Sublist(listOf(Item(value)))))
}
}
private var index = 0
private fun parseItem(input: String): Node = when (input[index]) {
'[' -> Node.Sublist(buildList { // start a new sublist
index++
while (index < input.length && input[index] != ']') { // we reached the end of the current sublist
add(parseItem(input))
}
index++
})
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> Node.Item(buildString {
while (input[index].isDigit()) {
this.append(input[index])
index++
}
}.toInt())
else -> {
// handle comma
index++
parseItem(input)
}
} | 0 | Kotlin | 0 | 0 | 4ff5afb730d8bc074eb57650521a03961f86bc95 | 3,147 | AOC2022 | Apache License 2.0 |
src/Day02.kt | ghasemdev | 572,632,405 | false | {"Kotlin": 7010} | import RoundAction.*
private enum class Action(private val score: Int) {
Rock(1), Paper(2), Scissors(3);
infix fun compare(action: Action): Int = when {
this == action -> Draw.score
this == Rock && action == Scissors -> Win.score
this == Scissors && action == Paper -> Win.score
this == Paper && action == Rock -> Win.score
else -> Lose.score
} + score
infix fun compare(action: RoundAction): Int = action.score + when (this) {
Rock -> when (action) {
Lose -> Scissors.score
Win -> Paper.score
Draw -> Rock.score
}
Paper -> when (action) {
Lose -> Rock.score
Win -> Scissors.score
Draw -> Paper.score
}
Scissors -> when (action) {
Lose -> Paper.score
Win -> Rock.score
Draw -> Scissors.score
}
}
companion object {
fun from(value: String): Action = when (value) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> throw IllegalStateException("Unknown action")
}
}
}
private enum class RoundAction(val score: Int) {
Lose(0), Win(6), Draw(3);
companion object {
fun from(value: String): RoundAction = when (value) {
"X" -> Lose
"Y" -> Draw
"Z" -> Win
else -> throw IllegalStateException("Unknown round action")
}
}
}
fun main() {
fun part1(input: List<String>): Int {
var result = 0
input.forEach { line ->
val (player1, player2) = line
.split(" ")
.map { Action.from(it) }
result += player2 compare player1
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
input.forEach { line ->
val (player1, action) = run {
val actions = line.split(" ")
Action.from(actions.first()) to RoundAction.from(actions.last())
}
result += player1 compare action
}
return result
}
// 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 | 1 | 7aa5e7824c0d2cf2dad94ed8832a6b9e4d36c446 | 2,446 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | sms-system | 572,903,655 | false | {"Kotlin": 4632} | typealias Moves = List<Pair<Int, Int>>
fun Moves.calculateScore(): Int = fold(0) { acc, move ->
var roundResult =
if (move.first == move.second) { 1 }
else { if (move.second > move.first) { 2 } else { 0 } }
if (move.first == 1 && move.second == 3) { roundResult = 0 }
else if (move.first == 3 && move.second == 1) { roundResult = 2 }
acc + move.second + roundResult * 3
}
fun main() {
val weight = mapOf("A" to 1, "B" to 2, "C" to 3, "X" to 1, "Y" to 2, "Z" to 3)
fun getListOfMoves(input: List<String>): Moves = input.map {
it
.split(" ")
.map { weight[it]!! }
.zipWithNext()
.single()
}
fun part1(input: List<String>): Int {
return getListOfMoves(input)
.calculateScore()
}
fun part2(input: List<String>): Int {
return getListOfMoves(input)
.map {
val opponentMove = if (it.second === 1) { it.first + 1 }
else { it.first }
val yourMove = if (it.second === 2) { opponentMove }
else { opponentMove % 3 + 1 }
Pair(it.first, yourMove)
}
.calculateScore()
}
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 | 266dd4e52f3b01912fbe2aa23d1ee70d1292827d | 1,432 | adventofcode-2022-kotlin | Apache License 2.0 |
src/Day12.kt | davedupplaw | 573,042,501 | false | {"Kotlin": 29190} | fun main() {
fun bestSteps(map: List<List<Int>>, x: Int, y: Int, current: Int): List<Pair<Int, Int>> {
val output = mutableListOf<Pair<Int, Int>>()
val allowedStep = listOf(current, current + 1, 'E'.code)
if (x > 0 && y > 0 && map[y - 1][x - 1] in allowedStep) {
output.add(Pair(x - 1, y - 1))
}
if (x < map[0].size - 1 && y > 0 && map[y - 1][x + 1] in allowedStep) {
output.add(Pair(x + 1, y - 1))
}
if (x < map[0].size - 1 && y < map.size - 1 && map[y + 1][x + 1] in allowedStep) {
output.add(Pair(x + 1, y + 1))
}
if (x > 0 && y < map.size - 1 && map[y + 1][x - 1] in allowedStep) {
output.add(Pair(x - 1, y + 1))
}
if (y > 0 && map[y - 1][x] in allowedStep) {
output.add(Pair(x, y - 1))
}
if (x > 0 && map[y][x - 1] in allowedStep) {
output.add(Pair(x - 1, y))
}
if (y < map.size - 1 && map[y + 1][x] in allowedStep) {
output.add(Pair(x, y + 1))
}
if (x < map[0].size - 1 && map[y][x + 1] in allowedStep) {
output.add(Pair(x + 1, y))
}
return output
}
fun followPath(map: List<List<Int>>, x: Int, y: Int, currentPath: ArrayDeque<Pair<Int, Int>>): Pair<Int, Int>? {
println("Current position: ${map[y][x].toChar()} @ (${x},${y})")
println(currentPath.map { """(${it.first},${it.second})""" })
val possibleSteps = bestSteps(map, x, y, if (map[y][x] == 'S'.code) 'a'.code else map[y][x])
val stepsToTry = possibleSteps - currentPath
println(" -> Possible steps $possibleSteps")
println(" -> Steps to try $stepsToTry")
var cx = x
var cy = y
stepsToTry.forEach { nextStep ->
cx = nextStep.first
cy = nextStep.second
if (map[y][x] == 'E'.code) {
return nextStep
} else {
return followPath(map, cx, cy, ArrayDeque(currentPath + nextStep))
}
}
return null
}
fun part1(input: List<String>): Int {
val map = input.map { line -> line.map { it.code } }
val startY = map.indexOfFirst { it.contains('S'.code) }
val startX = map[startY].indexOfFirst { it == 'S'.code }
var x = startX
var y = startY
var ended = false
var currentPath = ArrayDeque(listOf(x to y))
followPath(map, x, y, currentPath)
return currentPath.size
}
fun part2(input: List<String>): Int {
return 2
}
val test = readInput("Day12.test")
val part1test = part1(test)
println("part1 test: $part1test")
check(part1test == 31)
// val part2test = part2(test)
// println("part2 test: $part2test")
// check(part2test == 70)
val input = readInput("Day12")
val part1 = part1(input)
println("Part1: $part1")
// val part2 = part2(input)
// println("Part2: $part2")
}
| 0 | Kotlin | 0 | 0 | 3b3efb1fb45bd7311565bcb284614e2604b75794 | 3,015 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | aamielsan | 572,653,361 | false | {"Kotlin": 9363} | fun main() {
fun part1(input: String): String {
val (crateInput, instructionInput) = input.split("\n\n")
val crates = crateInput.toCrates()
instructionInput
.toInstructions()
.forEach { (count, from, to) ->
val boxes = crates[from].takeLast(count).reversed()
crates[to].addAll(boxes)
repeat(count) {
crates[from].removeLast()
}
}
return crates.fold("") { acc, stack ->
acc + stack.last()
}
}
fun part2(input: String): String {
val (crateInput, instructionInput) = input.split("\n\n")
val crates = crateInput.toCrates()
instructionInput
.toInstructions()
.forEach { (count, from, to) ->
val boxes = crates[from].takeLast(count)
crates[to].addAll(boxes)
repeat(count) {
crates[from].removeLast()
}
}
return crates.fold("") { acc, stack ->
acc + stack.last()
}
}
val input = readInputToText("Day05")
println(part1(input))
println(part2(input))
}
private fun String.toCrates() =
replace("[\\[\\]]".toRegex(), "")
.replace("\\s\\s\\s\\s".toRegex(), " ")
.lines()
.let { it.take(it.size - 1) }
.map { it.split(" ") }
.let { Pair(it, it.maxBy { line -> line.size }.size) }
.let {
val (lines, cratesCount) = it
lines.foldRight(MutableList(cratesCount) { mutableListOf<String>() }) { line, acc ->
line.forEachIndexed { index, s ->
acc[index].add(s)
acc[index] = acc[index].filter(String::isNotEmpty).toMutableList()
}
acc
}
}
private fun String.toInstructions() =
lines()
.mapNotNull { "move (\\d+) from (\\d+) to (\\d+)".toRegex().matchEntire(it) }
.map { it.groupValues.drop(1) }
.map { listOf(it[0].toInt(), it[1].toInt() - 1, it[2].toInt() - 1) }
| 0 | Kotlin | 0 | 0 | 9a522271bedb77496e572f5166c1884253cb635b | 2,133 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day12.kt | akijowski | 574,262,746 | false | {"Kotlin": 56887, "Shell": 101} | fun main() {
val directions = listOf(
-1 to 0,
1 to 0,
0 to -1,
0 to 1
)
fun part1(input: List<String>): Int {
var start: GraphNode? = null
var end: GraphNode? = null
// graph weights
val heights = buildList {
for (y in input.indices) {
// row of heights
val hs = buildList {
for (x in input[y].indices) {
var c = input[y][x]
when(c) {
'S' -> {
start = GraphNode(c, x, y)
c = 'a'
}
'E' -> {
end = GraphNode(c, x, y)
c = 'z'
}
}
add(c - 'a')
}
}
add(hs)
}
}
val adjList = buildMap {
for (y in input.indices) {
for (x in input[y].indices) {
// nodes that are within 1 step
this[GraphNode(input[y][x], x, y)] = buildList {
directions.forEach { (dx, dy) ->
val a = x + dx
val b = y + dy
if (b in input.indices && a in input[y].indices) {
if (heights[b][a] - heights[y][x] <= 1) {
add(GraphNode(input[b][a], a, b))
}
}
}
}
}
}
}
val b = BFSGraphSearch(adjList, start!!)
return b.run(end!!)
}
fun part2(input: List<String>): Int {
var start: GraphNode? = null
val ends = mutableSetOf<GraphNode>()
// graph weights
val heights = buildList {
for (y in input.indices) {
// row of heights
val hs = buildList {
for (x in input[y].indices) {
var c = input[y][x]
// go backwards
when (c) {
'S' -> {
ends += GraphNode(c, x, y)
c = 'a'
}
'a' -> ends += GraphNode(c, x, y)
'E' -> {
start = GraphNode(c, x, y)
c = 'z'
}
}
add(c - 'a')
}
}
add(hs)
}
}
val adjList = buildMap {
for (y in input.indices) {
for (x in input[y].indices) {
// next steps (going backwards)
this[GraphNode(input[y][x], x, y)] = buildList {
directions.forEach { (dx, dy) ->
val a = x + dx
val b = y + dy
if (b in input.indices && a in input[y].indices) {
// can we step backwards?
if (heights[y][x] - heights[b][a] <= 1) {
add(GraphNode(input[b][a], a, b))
}
}
}
}
}
}
}
val g = Dijkstra(adjList, start!!)
return g.runAll(ends).minOf { it.value }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 84d86a4bbaee40de72243c25b57e8eaf1d88e6d1 | 4,047 | advent-of-code-2022 | Apache License 2.0 |
src/day4/Day04.kt | Johnett | 572,834,907 | false | {"Kotlin": 9781} | package day4
import readInput
fun main() {
fun getSectionRangePair(assignments: String): Pair<IntRange, IntRange> {
fun getRange(values: Pair<Int, Int>): IntRange = values.first..values.second
val sectionRanges = assignments.split(",").map { sections ->
sections.split("-").let { section ->
Pair(section.first().toInt(), section.last().toInt())
}
}
return Pair(getRange(sectionRanges.first()), getRange(sectionRanges.last()))
}
fun assignmentContains(pair: Pair<IntRange, IntRange>): Boolean =
(pair.first.first <= pair.second.first && pair.first.last >= pair.second.last) || (pair.second.first <= pair.first.first && pair.second.last >= pair.first.last)
fun assignmentOverlaps(pair: Pair<IntRange, IntRange>): Boolean =
pair.first.first in pair.second || (pair.first.last in pair.second && pair.second.first in pair.first) || pair.second.last in pair.first
fun part1(input: List<String>): Int {
var pairCount = 0
input.forEach { assignments ->
if (assignmentContains(getSectionRangePair(assignments))) pairCount++
}
return pairCount
}
fun part2(input: List<String>): Int {
var pairCount = 0
input.forEach { assignments ->
if (assignmentOverlaps(getSectionRangePair(assignments))) pairCount++
}
return pairCount
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day4/Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("day4/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | c8b0ac2184bdad65db7d2f185806b9bb2071f159 | 1,713 | AOC-2022-in-Kotlin | Apache License 2.0 |
src/Day14.kt | thpz2210 | 575,577,457 | false | {"Kotlin": 50995} | import kotlin.math.max
import kotlin.math.min
private class Solution14(input: List<String>) {
val paths = input.map { line -> line.split(" -> ").map { c -> c.split(",").map { it.toInt() } } }
val maxY = paths.flatten().maxOf { it[1] }
var initialCave = paths.flatMap { path ->
(1 until path.size).flatMap {
coordinatesBetween(path[it - 1][0], path[it - 1][1], path[it][0], path[it][1])
}
}.toSet()
fun coordinatesBetween(x0: Int, y0: Int, x1: Int, y1: Int): List<Coordinate> {
val minX = min(x0, x1)
val maxX = max(x0, x1)
val minY = min(y0, y1)
val maxY = max(y0, y1)
if (minX == maxX) return (minY..maxY).map { y -> Coordinate(minX, y) }
if (minY == maxY) return (minX..maxX).map { x -> Coordinate(x, minY) }
throw IllegalStateException()
}
fun part1(): Int {
val cave = initialCave.toMutableSet()
dropSand(cave)
return cave.size - initialCave.size
}
fun part2(): Int {
val cave = initialCave.toMutableSet()
dropSand2(cave)
return cave.size - initialCave.size
}
fun dropSand(cave: MutableSet<Coordinate>) {
while (true) {
var position = Coordinate(500, 0)
var nextPosition = findNextPosition(position, cave)
while (nextPosition != null) {
if (nextPosition.y > maxY) return
position = nextPosition
nextPosition = findNextPosition(position, cave)
}
cave.add(position)
}
}
fun dropSand2(cave: MutableSet<Coordinate>) {
while (true) {
var position = Coordinate(500, 0)
var nextPosition = findNextPosition(position, cave)
if (nextPosition == null) {
cave.add(position)
return
}
while (nextPosition != null) {
if (nextPosition.y > maxY + 1) {
break
}
position = nextPosition
nextPosition = findNextPosition(position, cave)
}
cave.add(position)
}
}
private fun findNextPosition(position: Coordinate, cave: Set<Coordinate>): Coordinate? {
val down = Coordinate(position.x, position.y + 1)
if (!cave.contains(down)) return down
val downLeft = Coordinate(position.x - 1, position.y + 1)
if (!cave.contains(downLeft)) return downLeft
val downRight = Coordinate(position.x + 1, position.y + 1)
if (!cave.contains(downRight)) return downRight
return null
}
}
fun main() {
val testSolution = Solution14(readInput("Day14_test"))
check(testSolution.part1() == 24)
check(testSolution.part2() == 93)
val solution = Solution14(readInput("Day14"))
println(solution.part1())
println(solution.part2())
}
| 0 | Kotlin | 0 | 0 | 69ed62889ed90692de2f40b42634b74245398633 | 2,916 | aoc-2022 | Apache License 2.0 |
src/year2022/day12/Day12.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day12
import readInputFileByYearAndDay
import readTestFileByYearAndDay
fun main() {
infix fun List<CharArray>.findMatching(toSearch: Char): Set<Pair<Int, Int>> {
val ret = mutableSetOf<Pair<Int, Int>>()
for (i in this.indices)
for (j in this[0].indices)
if (this[i][j] == toSearch)
ret.add(i to j)
return ret
}
fun countMinSteps(
startingPositions: MutableSet<Pair<Int, Int>>,
grid: List<CharArray>,
goal: Pair<Int, Int>
): Int {
val visited = Array(grid.size) { Array(grid[0].size) { false } }
var currentPositions = startingPositions.toMutableSet()
val directions = listOf(1 to 0, -1 to 0, 0 to 1, 0 to -1)
var steps = 0
while (true) {
steps++
val tmp: MutableSet<Pair<Int, Int>> = mutableSetOf()
currentPositions
.filterNot { visited[it.first][it.second] }
.forEach {
visited[it.first][it.second] = true
// find surrounding area that can be visited
directions.map { d -> it.first + d.first to it.second + d.second }
.filterNot { n -> (n.first < 0 || n.second < 0 || n.first >= grid.size || n.second >= grid[0].size || visited[n.first][n.second]) }
.filterNot { n -> grid[n.first][n.second] - 1 > grid[it.first][it.second] } // max height difference
.forEach { n -> tmp.add(n) }
if (tmp.contains(goal)) return steps
}
currentPositions = tmp
}
}
fun part1(input: List<String>): Int =
input.map { it.toCharArray() }.let {
val start = (it findMatching 'S').first()
it[start.first][start.second] = 'a' // to allow for easy ordering via Int value
val goal = (it findMatching 'E').first()
it[goal.first][goal.second] = 'z' // to allow for easy ordering via Int value
return countMinSteps(mutableSetOf(start), it, goal)
}
// What is Big O?
// https://i.redd.it/b9zi50qene5a1.png
fun part2(input: List<String>): Int =
input.map { it.toCharArray() }.let {
val start = (it findMatching 'S').first()
it[start.first][start.second] = 'a' // to allow for easy ordering via Int value
val goal = (it findMatching 'E').first()
it[goal.first][goal.second] = 'z' // to allow for easy ordering via Int value
return countMinSteps((it findMatching 'a').toMutableSet(), it, goal)
}
val testInput = readTestFileByYearAndDay(2022, 12)
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInputFileByYearAndDay(2022, 12)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 2,897 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2023/Day03.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2023
import net.voldrich.BaseDay
// https://adventofcode.com/2023/day/3
fun main() {
Day03().run()
}
class Day03 : BaseDay() {
val numberPattern = "\\d+".toRegex()
val specialCharPattern = "[^.\\d]".toRegex()
data class Line(val index: Int, val numbers: List<LineNum>, val specialChars: List<Pair<Int, String>>)
data class LineNum(val start: Int, val end: Int, val value: Int)
override fun task1(): Int {
val parsed = parseLines()
return parsed.flatMap { line ->
line.numbers.filter { findSpecialSymbol(parsed, line.index, it) }
}.sumOf { it.value }
}
override fun task2(): Int {
val parsed = parseLines()
return parsed.flatMap { line ->
line.specialChars.filter { it.second == "*" }.map { calculateGearNum(parsed, line.index, it) }
}.sumOf { it }
}
private fun calculateGearNum(parsed: List<Line>, index: Int, gear: Pair<Int, String>): Int {
val gearNums = collectNearbyLines(index, parsed).flatMap { it.numbers }
.filter { gear.first in (it.start - 1..it.end + 1) }
.map { it.value }
.toList()
return if (gearNums.size > 1) {
gearNums.reduce { a, b -> a * b }
} else {
0
}
}
private fun parseLines() = input.lines().filter { it.isNotBlank() }.mapIndexed { index, line ->
val numbers = numberPattern.findAll(line)
.map { LineNum(it.range.start, it.range.endInclusive, it.value.toInt()) }
.toList()
val specialChars = specialCharPattern.findAll(line)
.map { it.range.start to it.value }
.toList()
Line(index, numbers, specialChars)
}.toList()
private fun findSpecialSymbol(parsed: List<Line>, index: Int, number: LineNum): Boolean {
return collectNearbyLines(index, parsed).flatMap { it.specialChars }
.any { it.first in (number.start - 1..number.end + 1) }
}
private fun collectNearbyLines(index: Int, parsed: List<Line>): List<Line> {
val lines = mutableListOf<Line>()
if (index - 1 >= 0) {
lines.add(parsed.get(index - 1))
}
lines.add(parsed.get(index))
if (index + 1 < parsed.size) {
lines.add(parsed.get(index + 1))
}
return lines
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 2,384 | advent-of-code | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2021/day20/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2021.day20
import com.kingsleyadio.adventofcode.util.readInput
fun solution(input: List<BooleanArray>, algorithm: String, sampleSize: Int): Int {
fun enhance(image: List<BooleanArray>, infinityPixel: Boolean): Pair<List<BooleanArray>, Boolean> {
val enhanced = List(image.size + 2) { i ->
BooleanArray(image.size + 2) { j ->
val key = (0..8).map { index ->
val y = index / 3 + i - 2
val x = index % 3 + j - 2
if (image.getOrNull(y)?.getOrNull(x) ?: infinityPixel) '1' else '0'
}.joinToString("").toInt(2)
algorithm[key] == '#'
}
}
val infinityKey = (if (infinityPixel) "1" else "0").repeat(9)
val newInfinityPixel = algorithm[infinityKey.toInt(2)] == '#'
return enhanced to newInfinityPixel
}
val (enhanced, _) = (1..sampleSize).fold(input to false) { (f, s), _ -> enhance(f, s) }
return enhanced.sumOf { row -> row.count { it } }
}
fun main() {
val lines = readInput(2021, 20).readLines()
val algorithm = lines[0]
val image = lines.drop(2).map { line -> line.map { it == '#' }.toBooleanArray() }
println(solution(image, algorithm, 2))
println(solution(image, algorithm, 50))
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,329 | adventofcode | Apache License 2.0 |
src/Day05.kt | brigittb | 572,958,287 | false | {"Kotlin": 46744} | fun main() {
fun prepareConfiguration(input: List<String>): MutableList<ArrayDeque<String>> {
val stacks = input
.first { it.contains("1") }
.split(" ")
.map { it.trim() }
.map { ArrayDeque<String>() }
.toMutableList()
input
.filter { it.contains("[") }
.map { it.asSequence().chunked(4) }
.map { values -> values.map { it.joinToString("").trim() } }
.forEach {
it.forEachIndexed { index, value ->
if (value.isNotEmpty()) {
stacks[index].addLast(value)
}
}
}
return stacks
}
fun getInstructions(input: List<String>) = input
.filter { it.startsWith("move") }
.map { instruction ->
instruction
.split(Regex("[a-z]{2,4}"))
.filterNot { it.isEmpty() }
.map { it.trim() }
}
.map { (count, source, destination) ->
Triple(
count.toInt(),
source.toInt(),
destination.toInt(),
)
}
fun getTopCrates(stacks: MutableList<ArrayDeque<String>>): String =
stacks
.map { it.first() }
.joinToString(separator = "") {
it.replace(Regex("[\\[\\]]"), "")
}
fun part1(input: List<String>): String {
val stacks = prepareConfiguration(input)
getInstructions(input).forEach { (count, source, destination) ->
for (i in 1 until count + 1) {
val element = stacks[source - 1].removeFirst()
stacks[destination - 1].addFirst(element)
}
}
return getTopCrates(stacks)
}
fun part2(input: List<String>): String {
val stacks = prepareConfiguration(input)
getInstructions(input).forEach { (count, source, destination) ->
val sourceList = stacks[source - 1].toList()
val elementsToKeep = sourceList.takeLast(sourceList.size - count)
stacks[source - 1] = ArrayDeque(elementsToKeep)
val elementsToMove = sourceList.take(count)
stacks[destination - 1].addAll(0, elementsToMove)
}
return stacks
.map { it.first() }
.joinToString(separator = "") { it.replace(Regex("[\\[\\]]"), "") }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 470f026f2632d1a5147919c25dbd4eb4c08091d6 | 2,742 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | zuevmaxim | 572,255,617 | false | {"Kotlin": 17901} | private fun priority(c: Char): Int {
if (c in 'a'..'z') return c - 'a' + 1
check(c in 'A'..'Z')
return c - 'A' + 27
}
private fun part1(input: List<String>) = input.sumOf { line ->
val m = line.length / 2
val (left, right) = line.take(m).toSet() to line.drop(m).toSet()
val intersect = left.intersect(right)
intersect.sumOf { priority(it) }
}
private fun part2(input: List<String>): Int = input.withIndex().groupBy { it.index / 3 }.map { g -> g.value.map { it.value } }.sumOf { group ->
group[0].toSet().intersect(group[1].toSet()).intersect(group[2].toSet()).sumOf { priority(it) }
}
fun main() {
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 34356dd1f6e27cc45c8b4f0d9849f89604af0dfd | 836 | AOC2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day03/Day03.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day03
import nl.sanderp.aoc.common.measureDuration
import nl.sanderp.aoc.common.prettyPrint
import nl.sanderp.aoc.common.readResource
data class Result(val a: String, val b: String) {
val product by lazy { a.toLong(2) * b.toLong(2) }
}
fun main() {
val input = readResource("Day03.txt").lines()
val (answer1, duration1) = measureDuration<Result> { partOne(input) }
println("Part one: ${answer1.product} (took ${duration1.prettyPrint()})")
val (answer2, duration2) = measureDuration<Result> { partTwo(input) }
println("Part two: ${answer2.product} (took ${duration2.prettyPrint()})")
}
private fun partOne(input: List<String>): Result {
val bitCounts = (0 until input.first().length).map { i -> input.map { it[i] }.bitCount() }
val gamma = bitCounts.map { it.max.first }.joinToString("")
val epsilon = bitCounts.map { it.min.first }.joinToString("")
return Result(gamma, epsilon)
}
private fun partTwo(input: List<String>): Result {
var oxygenGenerator = input
var co2Scrubber = input
for (i in 0 until input.first().length) {
val oxygenGeneratorBit = oxygenGenerator.map { it[i] }.bitCount().maxOrDefault
oxygenGenerator = oxygenGenerator.filter { it[i] == oxygenGeneratorBit }
val co2ScrubberBit = co2Scrubber.map { it[i] }.bitCount().minOrDefault
co2Scrubber = co2Scrubber.filter { it[i] == co2ScrubberBit }
}
return Result(oxygenGenerator.first(), co2Scrubber.first())
}
data class BitCount(val min: Pair<Char, Int>, val max: Pair<Char, Int>) {
val minOrDefault = if (min.second < max.second) min.first else '0'
val maxOrDefault = if (max.second > min.second) max.first else '1'
}
private fun List<Char>.bitCount(): BitCount {
val count = this.groupingBy { it }.eachCount()
return BitCount(min = count.minByOrNull { it.value }!!.toPair(), max = count.maxByOrNull { it.value }!!.toPair())
} | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,946 | advent-of-code | MIT License |
src/Day07.kt | A55enz10 | 573,364,112 | false | {"Kotlin": 15119} | fun main() {
fun part1(input: List<String>): Int {
return getFilesystem(input).directoryList.filter { it.getSize() <= 100000 }.sumOf { it.getSize() }
}
fun part2(input: List<String>): Int {
val memToFree = getFilesystem(input).fileList.sumOf { it.getSize() } - 40000000
return getFilesystem(input).directoryList
.filter { it.getSize() >= (memToFree) }
.minByOrNull { it.getSize() }
?.getSize() ?: -1
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
fun getFilesystem(input: List<String>): MyFileSystem {
val fs = MyFileSystem("/")
var currentDir = fs.root
input.forEach { line ->
if (line.startsWith("$")) {// it's a command
if (line.contains(" cd ")) {
val nextDirName = line.split(" cd ")[1]
currentDir = if (nextDirName == "..") {
// go up one directory
currentDir.parent?:currentDir
} else {
// go down one directory
currentDir.subdirectories.firstOrNull { dir -> dir.name == nextDirName } ?: currentDir
}
}
} else { // it's file or directory
val (objSize, objName) = line.split(" ")
if (objSize == "dir") {
currentDir.subdirectories
.filter { dir -> dir.name == objName }
.ifEmpty { currentDir.addSubdirectory(objName) }
} else {
currentDir.files
.filter { file -> file.name == objName }
.ifEmpty { currentDir.addFile(objName, objSize.toInt()) }
}
}
}
return fs
}
class MyFileSystem(fsName: String) {
val root = Directory(this, null, fsName, "/")
val directoryList = mutableListOf<Directory>()
val fileList = mutableListOf<File>()
}
class Directory(private val fs: MyFileSystem, val parent: Directory?, val name: String, path: String) {
private val fullPath = if (name == "/") "/" else "$path$name/"
var subdirectories = mutableListOf<Directory>()
var files = mutableListOf<File>()
fun addSubdirectory(subName: String) {
val newDir = Directory(fs, this, subName, this.fullPath)
subdirectories.add(newDir)
fs.directoryList.add(newDir)
}
fun addFile(fileName: String, fileSize: Int) {
val newFile = File(fileName, fileSize)
files.add(newFile)
fs.fileList.add(newFile)
}
fun getSize(): Int {
var sum = 0
for (i in 0 until files.size) sum += files[i].getSize()
for (i in 0 until subdirectories.size) sum += subdirectories[i].getSize()
return sum
}
}
open class File(open val name: String, private val fileSize: Int) {
open fun getSize(): Int {
return fileSize
}
}
| 0 | Kotlin | 0 | 1 | 8627efc194d281a0e9c328eb6e0b5f401b759c6c | 2,942 | advent-of-code-2022 | Apache License 2.0 |
src/day02/Day02.kt | ankushg | 573,188,873 | false | {"Kotlin": 7320} | object Day02 : Solution<Int>(
dayNumber = "02",
part1ExpectedAnswer = 15,
part2ExpectedAnswer = 12
) {
// region helpers
private fun <T> List<T>.asPair(): Pair<T, T> = this[0]!! to this[1]!!
private fun scorePair(pair: Pair<Shape, Shape>): Int {
return pair.second.score + determineResult(pair.first, pair.second).score
}
enum class Shape(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3)
}
enum class GameResult(val score: Int) {
LOSS(0), DRAW(3), WIN(6)
}
// gameResultsByOurShapeByOpponentShape[theirShape][ourshape] = result
private val gameResultsByOurShapeByOpponentShape = mapOf(
Shape.ROCK to mapOf(
Shape.ROCK to GameResult.DRAW,
Shape.PAPER to GameResult.WIN,
Shape.SCISSORS to GameResult.LOSS
),
Shape.PAPER to mapOf(
Shape.ROCK to GameResult.LOSS,
Shape.PAPER to GameResult.DRAW,
Shape.SCISSORS to GameResult.WIN
),
Shape.SCISSORS to mapOf(
Shape.ROCK to GameResult.WIN,
Shape.PAPER to GameResult.LOSS,
Shape.SCISSORS to GameResult.DRAW
)
)
private fun determineResult(theirShape: Shape, ourShape: Shape): GameResult {
return gameResultsByOurShapeByOpponentShape[theirShape]!![ourShape]!!
}
// endregion
// region parsing
private val shapeCodeMap = mapOf(
"A" to Shape.ROCK,
"B" to Shape.PAPER,
"C" to Shape.SCISSORS,
// only used in Part 1
"X" to Shape.ROCK,
"Y" to Shape.PAPER,
"Z" to Shape.SCISSORS
)
private val resultCodeMap = mapOf(
"X" to GameResult.LOSS,
"Y" to GameResult.DRAW,
"Z" to GameResult.WIN
)
// endregion
// region Part1
override fun part1(input: List<String>): Int {
return parseInputPart1(input)
.sumOf(::scorePair)
}
private fun parseInputPart1(input: List<String>): List<Pair<Shape, Shape>> {
return input.map { row ->
row.split(" ").map { shapeCode -> shapeCodeMap[shapeCode]!! }.asPair()
}
}
// endregion
// region Part2
override fun part2(input: List<String>): Int {
return parseInputPart2(input)
.map(::determineShapesFromResult)
.sumOf(::scorePair)
}
private fun parseInputPart2(input: List<String>): List<Pair<Shape, GameResult>> {
return input.map { it.split(" ").asPair() }
.map { (them, desiredResult) ->
shapeCodeMap[them]!! to resultCodeMap[desiredResult]!!
}
}
private fun determineShapesFromResult(input: Pair<Shape, GameResult>): Pair<Shape, Shape> {
val (them, desiredResult) = input
return gameResultsByOurShapeByOpponentShape[them]!!
.firstNotNullOf { (candidateShape, result) ->
if (result == desiredResult) them to candidateShape else null
}
}
//endregion
}
fun main() {
Day02.main()
}
| 0 | Kotlin | 0 | 0 | b4c93b6f12f5677173cb9bacfe5aa4ce4afa5667 | 3,058 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/y2023/day13_a/Day13.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2023.day13_a
import util.InputReader
import util.timeIt
import kotlin.math.pow
class Day13(val input: String) {
private val grids = input.split("\n\n").map { it.lines() }
fun partOne(): Int {
return grids.sumOf { grid ->
grid.findMirror()?.let { it * 100 }
?: grid.cols().findMirror()
?: error("No mirror found")
}
}
fun partTwo(): Int {
for (grid in grids) {
grid.findSmudge()
}
return grids.sumOf { grid ->
grid.findSmudge().let { (row, col) -> row?.let { it * 100 } ?: col ?: error("No smudge found") }
}
}
private fun <E> List<E>.findMirror(): Int? =
this.indices.firstOrNull { this.reflectsAt(it) }
private fun <E> List<E>.reflectsAt(index: Int): Boolean {
if (index == 0) return false
return this.reflectedPairsFrom(index).all { (left, right) -> left == right }
}
private fun <E> List<E>.reflectedPairsFrom(index: Int): Sequence<Pair<E, E>> {
var i = index
var j = index - 1
return generateSequence {
if (i < this.size && j >= 0) {
val pair = this[i] to this[j]
i += 1
j -= 1
pair
} else {
null
}
}
}
private fun List<String>.cols(): List<String> =
this.first().toString().indices
.map { i ->
this.map { it[i] }
.joinToString("")
}
private fun List<String>.findSmudge(): Pair<Int?, Int?> {
val originalRows = findMirror()
val originalCols = cols().findMirror()
for (y in indices) {
for (x in this[y].indices) {
val newGrid = flip(y, x)
val newRows = newGrid.findMirror()
val newCols = newGrid.cols().findMirror()
if (newRows != originalRows) return newRows to null
if (newCols != originalCols) return null to newCols
}
}
error("No smudge found!")
}
private fun List<String>.flip(y: Int, x: Int): List<String> {
val newGrid = this.toMutableList()
val flipped = if (this[y][x] == '#') "." else "#"
newGrid[y] = newGrid[y].replaceRange(x, x + 1, flipped)
return newGrid
}
}
fun main() {
timeIt {
val year = 2023
val day = 13
val exampleInput = InputReader.getExample(year, day)
val puzzleInput = InputReader.getPuzzle(year, day)
fun partOne(input: String) = Day13(input).partOne()
fun partTwo(input: String) = Day13(input).partTwo()
println("Example 1: ${partOne(exampleInput)}")
println("Part 1: ${partOne(puzzleInput)}")
println("Example 2: ${partTwo(exampleInput)}")
println("Part 2: ${partTwo(puzzleInput)}")
}
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 2,934 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day02.kt | Teg79 | 573,881,244 | false | {"Kotlin": 4306} | import Outcome.*
import Shape.*
enum class Shape(private val beats: String, val points: Int) {
ROCK("C", 1),
PAPER("A", 2),
SCISSORS("B", 3);
fun beats() = convertShape(beats)
}
fun convertShape(code: String) =
when (code) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw RuntimeException("$code is not a valid shape")
}
enum class Outcome(val points: Int) {
LOSE(0),
DRAW(3),
WIN(6),
}
fun convertOutcome(code: String) =
when (code) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw RuntimeException("$code is not a valid outcome")
}
data class Match(val opponent: Shape, val mine: Shape) {
fun points() = mine.points +
when (opponent) {
mine -> DRAW.points
else -> if (mine == opponent.beats()) LOSE.points else WIN.points
}
}
fun response(opponent: Shape, outcome: Outcome) =
when (outcome) {
DRAW -> opponent
LOSE -> opponent.beats()
WIN -> opponent.beats().beats()
}
fun main() {
fun calculatePoints(input: List<String>, mapper: (List<String>) -> Match) =
input
.map { it.split(" ") }
.map(mapper)
.sumOf { it.points() }
fun part1(input: List<String>) =
calculatePoints(input) {
Match(convertShape(it[0]), convertShape(it[1]))
}
fun part2(input: List<String>) =
calculatePoints(input) {
val opponent = convertShape(it[0])
Match(opponent, response(opponent, convertOutcome(it[1])))
}
// 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 | 735ed402e8dbee2011d75c71545c14589c0aabb4 | 1,923 | aoc-2022 | Apache License 2.0 |
y2020/src/main/kotlin/adventofcode/y2020/Day11.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2020
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec2
import adventofcode.util.vector.mooreDelta
import adventofcode.util.vector.mooreNeighbors
fun main() = Day11.solve()
object Day11 : AdventSolution(2020, 11, "Seating System") {
override fun solvePartOne(input: String) =
generateSequence(input.let(::ConwayGrid), ConwayGrid::next)
.zipWithNext()
.first { (old, new) -> old == new }
.first
.count()
override fun solvePartTwo(input: String): Any {
return generateSequence(input.let(::SparseGrid), SparseGrid::next)
.zipWithNext()
.first { (old, new) -> old == new }
.first
.count()
}
private data class ConwayGrid(private val grid: List<List<Char>>) {
constructor(input: String) : this(input.lines().map(String::toList))
fun count() = grid.sumOf { it.count('#'::equals) }
fun next() = grid.indices.map { y ->
grid[0].indices.map { x ->
typeInNextGeneration(Vec2(x, y), grid[y][x])
}
}.let(::ConwayGrid)
private fun typeInNextGeneration(v: Vec2, ch: Char): Char =
when (ch) {
'L' -> if (countNear(v) > 0) 'L' else '#'
'#' -> if (countNear(v) <= 4) '#' else 'L'
else -> '.'
}
private fun countNear(v: Vec2) =
v.mooreNeighbors()
.map { grid.getOrNull(it.y)?.getOrNull(it.x) }
.count { it == '#' }
}
private data class SparseGrid(private val grid: List<List<Char>>) {
constructor(input: String) : this(input.lines().map(String::toList))
fun count() = grid.sumOf { it.count('#'::equals) }
fun next() = grid.indices.map { y ->
grid[0].indices.map { x ->
typeInNextGeneration(Vec2(x, y), grid[y][x])
}
}.let(::SparseGrid)
private fun typeInNextGeneration(v: Vec2, ch: Char): Char =
when (ch) {
'L' -> if (countNear(v) > 0) 'L' else '#'
'#' -> if (countNear(v) <= 5) '#' else 'L'
else -> '.'
}
private fun countNear(v: Vec2): Int =
mooreDelta.map { delta ->
generateSequence(v, delta::plus)
.map { get(it) }
.drop(1)
.takeWhile { it != null }
.find { it != '.' }
}
.count { it == '#' }
private fun get(v: Vec2) = grid.getOrNull(v.y)?.getOrNull(v.x)
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,666 | advent-of-code | MIT License |
src/Day04.kt | cypressious | 572,916,585 | false | {"Kotlin": 40281} | fun main() {
class Board(
val numbers: List<IntArray>
) {
val marked = Array(numbers.size) { BooleanArray(numbers[0].size) }
fun mark(n: Int) {
for ((rowIndex, row) in numbers.withIndex()) {
for ((columnIndex, x) in row.withIndex()) {
if (x == n) {
marked[rowIndex][columnIndex] = true
return
}
}
}
}
fun hasWinner(): Boolean {
return marked.any { row -> row.all { it } } ||
marked[0].indices.any { rowIndex -> marked.all { row -> row[rowIndex] } }
}
fun sumOfUnmarked(): Int {
var sum = 0
for ((rowIndex, row) in numbers.withIndex()) {
for ((columnIndex, x) in row.withIndex()) {
if (!marked[rowIndex][columnIndex]) {
sum += x
}
}
}
return sum
}
}
fun parse(input: List<String>): Pair<List<Int>, List<Board>> {
val numbers = input[0].split(',').map(String::toInt)
val boards = mutableListOf<Board>()
var currentBoard = mutableListOf<IntArray>()
for (line in input.drop(2)) {
if (line.isBlank()) {
boards += Board(currentBoard)
currentBoard = mutableListOf()
} else {
currentBoard += line.split(' ').filter { it.isNotBlank() }.map(String::toInt).toIntArray()
}
}
if (currentBoard.isNotEmpty()) {
boards += Board(currentBoard)
}
return numbers to boards
}
fun part1(input: List<String>): Int {
val (numbers, boards) = parse(input)
for (n in numbers) {
for (board in boards) {
board.mark(n)
if (board.hasWinner()) {
return board.sumOfUnmarked() * n
}
}
}
return 0
}
fun part2(input: List<String>): Int {
val (numbers, boards) = parse(input)
for (n in numbers) {
for (board in boards) {
board.mark(n)
if (boards.all { it.hasWinner() }) {
return board.sumOfUnmarked() * n
}
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 4512)
check(part2(testInput) == 1924)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 169fb9307a34b56c39578e3ee2cca038802bc046 | 2,707 | AdventOfCode2021 | Apache License 2.0 |
src/Day15.kt | buongarzoni | 572,991,996 | false | {"Kotlin": 26251} | import kotlin.math.abs
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
private const val ROW = 2_000_000
private const val TUNING_FREQUENCY_MULTIPLIER = 4_000_000
fun solveDay15() {
val lines = readInput("Day15")
solve(lines)
}
var minX = 0
var minY = 0
var maxX = 0
var maxY = 0
private fun solve(
lines: List<String>,
) {
val sensorsRadius = mutableMapOf<Position, Int>()
val sensors = mutableSetOf<Position>()
val beacons = mutableSetOf<Position>()
val invalidPositions = mutableSetOf<Position>()
lines.forEach { line ->
val sensor = line.getSensor()
val beacon = line.getBeacon()
if (sensor.y == ROW) sensors.add(sensor)
if (beacon.y == ROW) beacons.add(beacon)
val distance = sensor distance beacon
sensorsRadius[sensor] = distance +1
if (ROW in (sensor.y - distance)..(sensor.y + distance)) {
for (x in (sensor.x - distance + abs(sensor.y - ROW))..(sensor.x + distance - abs(sensor.y - ROW))) {
invalidPositions.add(Position(x, ROW))
}
}
}
val part1 = invalidPositions.size - beacons.size - sensors.size
println("Solution part 1 : $part1")
val range = 0 .. TUNING_FREQUENCY_MULTIPLIER
val distress = sensorsRadius.flatMap { (sensor, distance) ->
(-distance .. distance).flatMap { xDelta ->
val yDelta = distance -xDelta.absoluteValue
listOf(
Position(sensor.x + xDelta, sensor.y - yDelta),
Position(sensor.x + xDelta, sensor.y + yDelta),
).filter { (it.x in range && (it.y in range)) }
}
}.first { point -> sensorsRadius.all { it.key distance point >= it.value } }
val part2 = distress.x.toLong() * TUNING_FREQUENCY_MULTIPLIER + distress.y
println("Solution part 2 : $part2")
}
data class Position(
val x: Int,
val y: Int,
) {
infix fun distance(other: Position) = abs(x - other.x) + abs(y - other.y)
}
private fun String.getSensor(): Position {
val (x, y) = substringAfter("Sensor at x=")
.substringBefore(":")
.split(", y=")
.map(String::toInt)
maxX = max(maxX, x)
minX = min(minX, x)
maxY = max(maxY, y)
minY = min(minY, y)
return Position(x, y)
}
private fun String.getBeacon(): Position {
val (x, y) = substringAfter("closest beacon is at x=")
.split(", y=")
.map(String::toInt)
minX = min(minX, x)
maxX = max(maxX, x)
minY = min(minY, y)
maxY = max(maxY, y)
return Position(x, y)
}
| 0 | Kotlin | 0 | 0 | 96aadef37d79bcd9880dbc540e36984fb0f83ce0 | 2,589 | AoC-2022 | Apache License 2.0 |
2018/kotlin/day24p2/src/main.kt | sgravrock | 47,810,570 | false | {"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488} | import kotlin.math.max
import kotlin.system.measureTimeMillis
fun main(args: Array<String>) {
val ms = measureTimeMillis {
val classLoader = UnitGroup::class.java.classLoader
val input = classLoader.getResource("input.txt").readText()
val armies = parseArmies(input)
println(fightUntilDone(armies))
}
println("in ${ms}ms")
}
data class UnitGroup(
val id: Int,
val army: String,
var numUnits: Int,
val hitPoints: Int,
val attack: Int,
val attackType: String,
val weaknesses: List<String>,
val immunities: List<String>,
val initiative: Int
) {
fun effectivePower(): Int {
return numUnits * attack
}
fun damageDealtTo(other: UnitGroup): Int {
assert(other.army != army)
return if (attackType in other.immunities) {
0
} else if (attackType in other.weaknesses) {
effectivePower() * 2
} else {
effectivePower()
}
}
fun receiveDamage(damage: Int) {
val unitsKilled = damage / hitPoints
numUnits = max(0, numUnits - unitsKilled)
}
}
fun fightUntilDone(groups: List<UnitGroup>): Int {
while (groups.filter { it.numUnits > 0 }.map { it.army }.distinct().size > 1) {
fight(groups)
}
return groups.sumBy { it.numUnits }
}
fun fight(groups: List<UnitGroup>) {
doAttacks(groups, selectTargets(groups))
}
fun selectTargets(groups: List<UnitGroup>): Map<UnitGroup, UnitGroup> {
val result = mutableMapOf<UnitGroup, UnitGroup>()
targetSelectionOrder(groups).forEach { attacker ->
val target = targetPreferenceOrder(groups, attacker, result)
.firstOrNull()
if (target != null && attacker.damageDealtTo(target) > 0) {
result[attacker] = target
}
}
return result
}
fun doAttacks(groups: List<UnitGroup>, targets: Map<UnitGroup, UnitGroup>) {
groups
.map { attacker -> Pair(attacker, targets[attacker]) }
.filter { (_, defender) -> defender != null }
.sortedByDescending { (attacker, _) -> attacker.initiative }
.forEach { (attacker, defender) ->
defender!!.receiveDamage(attacker.damageDealtTo(defender))
}
}
fun targetSelectionOrder(groups: List<UnitGroup>): List<UnitGroup> {
return groups
.filter { it.numUnits > 0 }
.sortedWith(DescendingCascadingComparator(
listOf(
{ g: UnitGroup -> g.effectivePower() },
{ g: UnitGroup -> g.initiative }
)
))
}
fun targetPreferenceOrder(
groups: List<UnitGroup>,
attacker: UnitGroup,
choicesSoFar: Map<UnitGroup, UnitGroup>
): List<UnitGroup> {
return groups
.filter {
it.army != attacker.army
&& it.numUnits > 0
&& !choicesSoFar.containsValue(it)
}
.sortedWith(DescendingCascadingComparator(
listOf(
{ g: UnitGroup -> attacker.damageDealtTo(g) },
{ g: UnitGroup -> g.effectivePower() },
{ g: UnitGroup -> g.initiative }
)
))
}
class DescendingCascadingComparator(
val selectors: List<(UnitGroup) -> Int>
) : Comparator<UnitGroup> {
override fun compare(a: UnitGroup, b: UnitGroup): Int {
for (sel in selectors) {
val c = sel(b).compareTo(sel(a))
if (c != 0) {
return c
}
}
return 0
}
}
fun parseArmies(input: String): List<UnitGroup> {
val chunks = input.split("\n\n")
return listOf(
parseArmy(chunks[0]),
parseArmy(chunks[1])
).flatten()
}
fun parseArmy(input: String): List<UnitGroup> {
val lines = input.lines()
val type = lines[0].replace(":", "")
return lines.drop(1).mapIndexed { i, s ->
parseUnitGroup(s, i + 1, type)
}
}
fun parseUnitGroup(input: String, id: Int, army: String): UnitGroup {
val m = unitGroupRegex.matchEntire(input)
?: throw Exception("Parse error: $input")
val (weaknesses, immunities) = parseCapabilities(
m.groups["capabilities"]?.value
)
return UnitGroup(
id = id,
army = army,
numUnits = m.groups["numUnits"]!!.value.toInt(),
hitPoints = m.groups["hitPoints"]!!.value.toInt(),
attack = m.groups["damage"]!!.value.toInt(),
attackType = m.groups["String"]!!.value,
weaknesses = weaknesses,
immunities = immunities,
initiative = m.groups["initiative"]!!.value.toInt()
)
}
private fun parseCapabilities(
input: String?
): Pair<List<String>, List<String>> {
if (input == null) {
return Pair(emptyList(), emptyList())
}
var weaknesses = emptyList<String>()
var immunities = emptyList<String>()
for (chunk in input.split("; ")) {
val (name, values) = chunk.split(" to ")
val caps = values.split(", ")
when (name) {
"weak" -> weaknesses = caps
"immune" -> immunities = caps
else -> throw Error("Expected weak or immune but got $name")
}
}
return Pair(weaknesses, immunities)
}
private val unitGroupRegex = Regex(
"^(?<numUnits>[0-9]+) units each with (?<hitPoints>[0-9]+) hit points " +
"(\\((?<capabilities>[^)]+)\\) )?with an attack that does " +
"(?<damage>[0-9]+) (?<String>[^ ]+) damage at initiative " +
"(?<initiative>[0-9]+)\$"
)
| 0 | Rust | 0 | 0 | ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3 | 5,508 | adventofcode | MIT License |
app/src/main/kotlin/day13/Day13.kt | KingOfDog | 433,706,881 | false | {"Kotlin": 76907} | package day13
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 13
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay13Part1, ::solveDay13Part2)
}
fun solveDay13Part1(input: List<String>): Int {
val sectionEnd = input.indexOf("")
val dots = parseDots(input, sectionEnd)
val folds = parseFolds(input, sectionEnd)
val paper = generatePaper(dots)
val foldPaper = paper.foldAlong(folds[0])
return foldPaper.flatten().count { it }
}
private fun parseDots(
input: List<String>,
sectionEnd: Int
): List<Pair<Int, Int>> {
val dots = input.subList(0, sectionEnd).map { line -> line.split(",").map { it.toInt() } }
.map { Pair(it[0], it[1]) }
return dots
}
private fun parseFolds(
input: List<String>,
sectionEnd: Int
): List<FoldInstruction> {
val regex = Regex("fold along (x|y)=(\\d+)")
val folds = input.subList(sectionEnd + 1, input.size)
.map { regex.find(it)!!.groupValues }
.map { FoldInstruction(it[1] == "y", it[2].toInt()) }
return folds
}
private fun generatePaper(dots: List<Pair<Int, Int>>): Array<Array<Boolean>> {
val width = dots.maxOf { it.first } + 1
val height = dots.maxOf { it.second } + 1
return Array(height) { y -> Array(width) { x -> dots.contains(Pair(x, y)) } }
}
fun solveDay13Part2(input: List<String>): Int {
val sectionEnd = input.indexOf("")
val dots = parseDots(input, sectionEnd)
val folds = parseFolds(input, sectionEnd)
val paper = generatePaper(dots)
val foldedPaper = folds.fold(paper) { paper, fold -> paper.foldAlong(fold) }
foldedPaper.print()
return -1
}
private fun Array<Array<Boolean>>.foldAlong(fold: FoldInstruction): Array<Array<Boolean>> {
val folded = if (fold.horizontal) {
this.sliceArray(0 until fold.foldPoint)
} else {
this.map { it.sliceArray(0 until fold.foldPoint) }.toTypedArray()
}
if (fold.horizontal) {
for (i in (fold.foldPoint + 1) until size) {
val offset = i - fold.foldPoint
val y = folded.size - offset
this[i].forEachIndexed { x, value ->
folded[y][x] = folded[y][x] || value
}
}
} else {
for (i in (fold.foldPoint + 1) until (this[0].size)) {
val offset = i - fold.foldPoint
val x = folded[0].size - offset
this.forEachIndexed { y, row ->
folded[y][x] = folded[y][x] || row[i]
}
}
}
return folded
}
private fun Array<Array<Boolean>>.print() {
forEach { row ->
row.forEach { print(if (it) 'X' else ' ') }
println()
}
}
data class FoldInstruction(val horizontal: Boolean, val foldPoint: Int)
| 0 | Kotlin | 0 | 0 | 576e5599ada224e5cf21ccf20757673ca6f8310a | 2,849 | advent-of-code-kt | Apache License 2.0 |
src/main/kotlin/day08/solution.kt | bukajsytlos | 433,979,778 | false | {"Kotlin": 63913} | package day08
import java.io.File
import java.util.*
fun main() {
val lines =
File("src/main/kotlin/day08/input.txt").readLines()
val signalToOutputList = lines.map { line ->
line.substringBefore(" | ").split(" ").map { it.toSortedSet() } to line.substringAfter(" | ").split(" ")
.map { it.toSortedSet() }
}
println(signalToOutputList.flatMap { it.second }.count { it.size in setOf(2, 3, 4, 7) })
println(signalToOutputList.sumOf { decodeNumber(it.first, it.second) })
}
/**
* Segments
* 111
* 2 3
* 2 3
* 444
* 5 6
* 5 6
* 777
*/
fun decodeNumber(uniqueSignalPatterns: List<SortedSet<Char>>, unknownNumber: List<SortedSet<Char>>): Int {
val segmentsToDigit = HashMap<SortedSet<Char>, Int>()
segmentsToDigit[uniqueSignalPatterns.first { it.size == 2 }] = 1
segmentsToDigit[uniqueSignalPatterns.first { it.size == 3 }] = 7
segmentsToDigit[uniqueSignalPatterns.first { it.size == 4 }] = 4
segmentsToDigit[uniqueSignalPatterns.first { it.size == 7 }] = 8
val segmentFrequencies = uniqueSignalPatterns.flatten()
.groupBy { it }
.mapValues { it.value.size }
val fifthSegmentChar = segmentFrequencies
.filter { it.value == 4 }.map { it.key }
.first()
val unknownFiveSegmentSignals = uniqueSignalPatterns.filter { it.size == 5 }.toMutableList()
val unknownSixSegmentSignals = uniqueSignalPatterns.filter { it.size == 6 }.toMutableList()
var segmentsRepresentingFive: SortedSet<Char>? = null
var segmentsRepresentingSix: SortedSet<Char>? = null
//5 with fifth segment is 6
for (fiveSegmentSignal in unknownFiveSegmentSignals) {
val fiveSegmentSignalWithFifthSegment = fiveSegmentSignal.toSortedSet()
fiveSegmentSignalWithFifthSegment.add(fifthSegmentChar)
if (unknownSixSegmentSignals.contains(fiveSegmentSignalWithFifthSegment)) {
segmentsRepresentingFive = fiveSegmentSignal
segmentsRepresentingSix = fiveSegmentSignalWithFifthSegment
unknownFiveSegmentSignals.remove(segmentsRepresentingFive)
unknownSixSegmentSignals.remove(segmentsRepresentingSix)
break
}
}
segmentsToDigit[segmentsRepresentingFive!!] = 5
segmentsToDigit[segmentsRepresentingSix!!] = 6
segmentsToDigit[unknownFiveSegmentSignals.first { it.contains(fifthSegmentChar) }] = 2
segmentsToDigit[unknownFiveSegmentSignals.first { !it.contains(fifthSegmentChar) }] = 3
segmentsToDigit[unknownSixSegmentSignals.first { it.contains(fifthSegmentChar) }] = 0
segmentsToDigit[unknownSixSegmentSignals.first { !it.contains(fifthSegmentChar) }] = 9
return unknownNumber.mapNotNull { segmentsToDigit[it] }.joinToString("").toInt()
}
| 0 | Kotlin | 0 | 0 | f47d092399c3e395381406b7a0048c0795d332b9 | 2,819 | aoc-2021 | MIT License |
src/Day04.kt | mddanishansari | 576,622,315 | false | {"Kotlin": 11861} | fun main() {
fun IntRange.contains(other: IntRange): Boolean {
return contains(other.max()) && contains(other.min())
}
fun IntRange.doesOverlap(other: IntRange): Boolean {
return contains(other.max()) || contains(other.min())
}
fun List<String>.pairOfRange(): List<Pair<IntRange, IntRange>> {
return map { it.split(",") }
.map {
val firstRangeMin = it.first().split("-").first().toInt()
val firstRangeMax = it.first().split("-").last().toInt()
val secondRangeMin = it.last().split("-").first().toInt()
val secondRangeMax = it.last().split("-").last().toInt()
Pair(firstRangeMin..firstRangeMax, secondRangeMin..secondRangeMax)
}
}
fun part1(input: List<String>): Int {
var fullyContainedPairs = 0
input.pairOfRange().forEach {
if (it.first.contains(it.second) || it.second.contains(it.first)) {
fullyContainedPairs++
}
}
return fullyContainedPairs
}
fun part2(input: List<String>): Int {
var overlappingPairs = 0
input.pairOfRange().forEach {
if (it.first.doesOverlap(it.second)|| it.second.doesOverlap(it.first)) {
overlappingPairs++
}
}
return overlappingPairs
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | e032e14b57f5e6c2321e2b02b2e09d256a27b2e2 | 1,657 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | freszu | 573,122,040 | false | {"Kotlin": 32507} | /**
* For [A,B,C,D,E,F] updated list [D,E,F] and returned list [A,B,C]
*/
private fun <T> MutableList<T>.removeFirst(count: Int) = List(count) { removeAt(0) }
private data class CraneMove(val count: Int, val from: Int, val to: Int)
private fun parse(input: String): Pair<List<ArrayDeque<Char>>, List<CraneMove>> {
val (stackDescription, movesDescription) = input.split("\n\n")
return parseStacks(stackDescription) to parseMoves(movesDescription)
}
private fun parseStacks(stackDescription: String): List<ArrayDeque<Char>> {
val stackDescriptionRows = stackDescription.split("\n").dropLast(1)
val range = 1..stackDescriptionRows.first().length step 4
val stacks = List(range.count()) { ArrayDeque<Char>() }
stackDescriptionRows.forEach { line ->
for (i in range) {
line[i].takeIf { it.isLetter() }
?.run { stacks[range.indexOf(i)].add(line[i]) }
}
}
return stacks
}
private fun parseMoves(movesDescription: String): List<CraneMove> {
val moveRegex = Regex("move (\\d+) from (\\d+) to (\\d+)")
return movesDescription
.split("\n")
.dropLast(1)
.map { line ->
val (count, from, to) = moveRegex.matchEntire(line)!!.destructured
CraneMove(count.toInt(), from.toInt() - 1, to.toInt() - 1)
}
}
fun main() {
fun crateMover9000(input: String): String {
val (stacks, moves) = parse(input)
moves.forEach { (count, from, to) ->
repeat(count) {
stacks[to].addFirst(stacks[from].removeFirst())
}
}
return stacks.map { it.first() }.joinToString("")
}
fun crateMover9001(input: String): String {
val (stacks, moves) = parse(input)
moves.forEach { (count, from, to) ->
stacks[to].addAll(0, stacks[from].removeFirst(count))
}
return stacks.map { it.first() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsString("Day05_test")
val dayInput = readInputAsString("Day05")
check(crateMover9000(testInput) == "CMZ")
println(crateMover9000(dayInput))
check(crateMover9001(testInput) == "MCD")
println(crateMover9001(dayInput))
}
| 0 | Kotlin | 0 | 0 | 2f50262ce2dc5024c6da5e470c0214c584992ddb | 2,285 | aoc2022 | Apache License 2.0 |
src/Day08.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | import kotlin.math.max
fun main() {
fun List<String>.toGrid(): List<List<Int>> = map { row -> row.map { it.digitToInt() } }
fun List<List<Int>>.dimensions() = Pair(size, first().size)
fun List<List<Int>>.columns(): List<List<Int>> {
val (_, columns) = dimensions()
val response = (1..columns).map { mutableListOf<Int>() }
forEach { row ->
row.forEachIndexed { index, col ->
response[index] += col
}
}
return response
}
fun part1(input: List<String>): Int {
val grid = input.toGrid()
val gridColumns = grid.columns()
val (rows, cols) = grid.dimensions()
var visible = 0
for (rowIndex in 0 until rows) {
for (colIndex in 0 until cols) {
val height = grid[rowIndex][colIndex]
val row = grid[rowIndex]
val col = gridColumns[colIndex]
if (
row.subList(0, colIndex).none { it >= height } ||
row.subList(colIndex + 1, row.size).none { it >= height } ||
col.subList(0, rowIndex).none { it >= height } ||
col.subList(rowIndex + 1, row.size).none { it >= height }
) {
visible++
}
}
}
return visible
}
fun part2(input: List<String>): Int {
val grid = input.toGrid()
val gridColumns = grid.columns()
val (rows, cols) = grid.dimensions()
var topScenicScore = 0
for (rowIndex in 1 until rows - 1) {
for (colIndex in 1 until cols - 1) {
val height = grid[rowIndex][colIndex]
val row = grid[rowIndex]
val col = gridColumns[colIndex]
var left = row.subList(0, colIndex).takeLastWhile { it < height }.count()
var right = row.subList(colIndex + 1, row.size).takeWhile { it < height }.count()
var top = col.subList(0, rowIndex).takeLastWhile { it < height }.count()
var bottom = col.subList(rowIndex + 1, row.size).takeWhile { it < height }.count()
// Add tree we stopped at, if we didn't reach border
if (left < colIndex) left++
if (right < (row.size - (colIndex + 1))) right++
if (top < rowIndex) top++
if (bottom < (row.size - (rowIndex + 1))) bottom++
val scenicScore = left * right * top * bottom
topScenicScore = max(topScenicScore, scenicScore)
}
}
return topScenicScore
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 2,860 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/day13/ShuttleSearch.kt | Pkshields | 318,658,287 | false | null | package dev.paulshields.aoc.day13
import dev.paulshields.aoc.common.readFileAsStringList
fun main() {
println(" ** Day 13: Shuttle Search ** \n")
val fileInput = readFileAsStringList("/day13/BusTimes.txt")
val leavingAirportTime = fileInput[0].toInt()
val busIds = fileInput[1]
.split(",")
val busToCatch = calculateTheEarliestAirportBus(leavingAirportTime, busIds)
val part1Result = busToCatch.busID * busToCatch.waitTime
println("The bus we need to get is ${busToCatch.busID}, leaving in ${busToCatch.waitTime} minutes. Result: $part1Result!")
val day2Result = findEarliestTimestampThatMatchesPattern(busIds)
println("The answer to the shuttle companies contest is $day2Result!")
}
fun calculateTheEarliestAirportBus(leavingAirportTime: Int, busIds: List<String>) = busIds
.mapNotNull { it.toIntOrNull() }
.map { BusWaitTime(it, it - (leavingAirportTime % it)) }
.sortedBy { it.waitTime }
.first()
fun findEarliestTimestampThatMatchesPattern(busIds: List<String>): Long {
val busInfo = busIds.mapIndexedNotNull { index, busId ->
busId.toIntOrNull()
?.let { BusInfo(it, index) }
}
var earliestTimestamp = 0L
var lowestCommonMultiple = 1L
for (i in 2..busInfo.size) {
earliestTimestamp = generateSequence { lowestCommonMultiple }
.mapIndexed { index, _ -> earliestTimestamp + (lowestCommonMultiple * index) }
.filter { possibleTimeValue ->
allBusesDepartAtCorrectOffset(possibleTimeValue, busInfo.take(i))
}.first()
lowestCommonMultiple = busInfo.take(i).fold(1) { a, b -> a * b.busId }
}
return earliestTimestamp
}
private fun allBusesDepartAtCorrectOffset(time: Long, busInfo: List<BusInfo>) =
busInfo.all { (time + it.minutesAfterFirstBus) % it.busId == 0L }
data class BusWaitTime(val busID: Int, val waitTime: Int)
data class BusInfo(val busId: Int, val minutesAfterFirstBus: Int)
| 0 | Kotlin | 0 | 0 | a7bd42ee17fed44766cfdeb04d41459becd95803 | 1,981 | AdventOfCode2020 | MIT License |
2022/kotlin/src/Day02.kt | tomek0123456789 | 573,389,936 | false | {"Kotlin": 5085} | fun main() {
fun part1(input: List<String>): Int {
val scoreMap = mapOf("A" to mapOf("X" to 3, "Y" to 6, "Z" to 0),
"B" to mapOf("X" to 0, "Y" to 3, "Z" to 6),
"C" to mapOf("X" to 6, "Y" to 0, "Z" to 3))
val choiceMap = mapOf("X" to 1, "Y" to 2, "Z" to 3)
/*
X Y Z
rock A 1 0 2
paper B 2 1 0
scissors C 0 2 1
*/
var result = 0
for (s in input) {
val line = s.split(" ")
result += scoreMap[line[0]]!![line[1]]!!
result += choiceMap[line[1]]!!
}
return result
}
fun part2(input: List<String>): Int {
val scoreMap = mapOf("A" to mapOf("X" to 3, "Y" to 4, "Z" to 8),
"B" to mapOf("X" to 1, "Y" to 5, "Z" to 9),
"C" to mapOf("X" to 2, "Y" to 6, "Z" to 7))
var result = 0
for (s in input) {
val line = s.split(" ")
result += scoreMap[line[0]]!![line[1]]!!
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5ee55448242ec79475057f43d34f19ae05933eba | 1,328 | aoc | Apache License 2.0 |
src/day11/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day11
import println
import readInput
fun main() {
class Galaxy(val id: Int, val x: Int, val y: Int)
class GalaxyGame() {
lateinit var galaxies: List<Galaxy>
val GALAXY = '#'
constructor(input: List<String>, emptySpaceMultiplier: Int = 2) : this() {
this.galaxies = calculateGalaxyCoordinates(input.map { it.toCharArray() }, emptySpaceMultiplier)
}
fun calculateGalaxyCoordinates(input: List<CharArray>, emptySpaceMultiplier: Int): List<Galaxy> {
val emptyRows = input.mapIndexed { index, row -> if (row.contains(GALAXY)) -1 else index }
.filter { it >= 0 }
.toList()
val emptyColumns = input[0].indices.map { column ->
if (input.indices.any { row -> input[row][column] == GALAXY}) - 1 else column
}.filter { it >= 0 }
.toList()
var id = 1
val galaxiesList = mutableListOf<Galaxy>()
input.forEachIndexed { rowNumber, row ->
row.forEachIndexed { columnNumber, char ->
if (char == GALAXY) {
var x = columnNumber + emptyColumns.count { it < columnNumber } * (emptySpaceMultiplier - 1)
var y = rowNumber + emptyRows.count {it < rowNumber} * (emptySpaceMultiplier - 1)
galaxiesList += Galaxy(id++, x, y)
}
}
}
return galaxiesList
}
fun calculateManhattanDistance(galaxy1: Galaxy, galaxy2: Galaxy): Int {
return Math.abs(galaxy2.x - galaxy1.x) + Math.abs(galaxy2.y - galaxy1.y)
}
fun getSumOfShortestDistances(): Long {
var sumOfShortestPaths = 0L
galaxies.forEachIndexed {index, galaxy1 ->
((index + 1)..<galaxies.size).asSequence().forEach { index2 ->
var distance = calculateManhattanDistance(galaxy1, galaxies[index2])
sumOfShortestPaths += distance
}
}
return sumOfShortestPaths
}
}
var testGalaxyGame = GalaxyGame(readInput("day11/test1"))
check(testGalaxyGame.getSumOfShortestDistances() == 374L)
var galaxyGame = GalaxyGame(readInput("day11/input"))
galaxyGame.getSumOfShortestDistances().println()
var testGalaxyGame2 = GalaxyGame(readInput("day11/test1"),10)
check(testGalaxyGame2.getSumOfShortestDistances() == 1030L)
var testGalaxyGame3 = GalaxyGame(readInput("day11/test1"),100)
check(testGalaxyGame3.getSumOfShortestDistances() == 8410L)
var galaxyGame2 = GalaxyGame(readInput("day11/input"), 1000000)
galaxyGame2.getSumOfShortestDistances().println()
} | 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 2,760 | advent-of-code-2023 | Apache License 2.0 |
day03/src/main/kotlin/Main.kt | rstockbridge | 225,212,001 | false | null | fun main() {
val inputAsLines = resourceFile("input.txt")
.readLines()
val wire1 = parseInput(inputAsLines[0])
val wire2 = parseInput(inputAsLines[1])
println("Part I: the solution is ${solvePartI(wire1, wire2)}.")
println("Part II: the solution is ${solvePartII(wire1, wire2)}.")
}
fun parseInput(inputLine: String): Wire {
val result = Wire()
val startingPoint = GridPoint2d.origin
val instructionList = inputLine.split(",")
var x = startingPoint.x
var y = startingPoint.y
instructionList.forEach { instruction ->
val gridDirection = getGridDirection(instruction[0]);
val magnitude = instruction.substring(1).toInt()
for (i in 1..magnitude) { // exclude starting point
when (gridDirection) {
GridDirection.N -> y += 1
GridDirection.E -> x += 1
GridDirection.S -> y -= 1
GridDirection.W -> x -= 1
}
result.addPoint(GridPoint2d(x, y))
}
}
return result
}
private fun getGridDirection(direction: Char): Any {
return when (direction) {
'U' -> GridDirection.N
'D' -> GridDirection.S
'L' -> GridDirection.W
'R' -> GridDirection.E
else -> throw IllegalStateException("This line should not be reached.")
}
}
fun solvePartI(wire1: Wire, wire2: Wire): Int {
return calculateDistanceToClosestIntersectionPoint(wire1, wire2)
}
fun solvePartII(wire1: Wire, wire2: Wire): Int {
return calculateMinTotalNumberOfSteps(wire1, wire2)
}
fun calculateDistanceToClosestIntersectionPoint(wire1: Wire, wire2: Wire): Int {
val startingPoint = GridPoint2d.origin
val sharedPoints = getSharedPoints(wire1, wire2)
val closestPoint = sharedPoints.minBy { it.l1DistanceTo(startingPoint) }!!
return closestPoint.l1DistanceTo(startingPoint)
}
private fun getSharedPoints(wire1: Wire, wire2: Wire): Set<GridPoint2d> {
return wire1.getPoints().intersect(wire2.getPoints())
}
fun calculateMinTotalNumberOfSteps(wire1: Wire, wire2: Wire): Int {
val sharedPoints = getSharedPoints(wire1, wire2)
return sharedPoints
.map { sharedPoint ->
val wire1Steps = wire1
.getPoints()
.indexOfFirst { wire1Point ->
wire1Point == sharedPoint
}
val wire2Steps = wire2
.getPoints()
.indexOfFirst { wire2Point ->
wire2Point == sharedPoint
}
wire1Steps + wire2Steps + 2 // need to add on 1 + 1 to account for starting point
}
.min()!!
}
| 0 | Kotlin | 0 | 0 | bcd6daf81787ed9a1d90afaa9646b1c513505d75 | 2,678 | AdventOfCode2019 | MIT License |
src/day22/Day22.kt | davidcurrie | 579,636,994 | false | {"Kotlin": 52697} | package day22
import java.io.File
import kotlin.reflect.KFunction3
fun main() {
val input = File("src/day22/input.txt").readText().split("\n\n")
val tiles = mutableSetOf<Pair<Int, Int>>()
val walls = mutableSetOf<Pair<Int, Int>>()
input[0].split("\n").forEachIndexed { row, s ->
s.toList().forEachIndexed { column, c ->
when (c) {
'.' -> tiles.add(Pair(column + 1, row + 1))
'#' -> walls.add(Pair(column + 1, row + 1))
}
}
}
val directions = input[1].toList().fold(emptyList<Any>()) { acc, c ->
when (c) {
'L' -> acc + 'L'
'R' -> acc + 'R'
else -> if (acc.isNotEmpty() && acc.last() is Int) (acc.dropLast(1) + ((acc.last() as Int * 10) + c.toString()
.toInt())) else (acc + c.toString().toInt())
}
}
println(solve(tiles, walls, directions, ::flatWrap))
println(solve(tiles, walls, directions, ::cubeWrap))
}
private fun solve(
tiles: Set<Pair<Int, Int>>,
walls: Set<Pair<Int, Int>>,
directions: List<Any>,
wrap: KFunction3<Set<Pair<Int, Int>>, Set<Pair<Int, Int>>, State, State>
): Int {
var state = State(tiles.filter { it.second == 1 }.minByOrNull { it.first }!!, 0)
val deltas = listOf(Pair(1, 0), Pair(0, 1), Pair(-1, 0), Pair(0, -1))
directions.forEach { direction ->
when (direction) {
'L' -> state = State(state.coord, (state.facing - 1).mod(deltas.size))
'R' -> state = State(state.coord, (state.facing + 1).mod(deltas.size))
else -> for (i in 1..direction as Int) {
var nextState = State(
Pair(
state.coord.first + deltas[state.facing].first,
state.coord.second + deltas[state.facing].second
), state.facing
)
if (nextState.coord !in (walls + tiles)) {
nextState = wrap(tiles, walls, nextState)
}
if (nextState.coord in walls) break
state = nextState
}
}
}
return state.password()
}
data class State(val coord: Pair<Int, Int>, val facing: Int) {
fun password() = 4 * coord.first + 1000 * coord.second + facing
}
private fun flatWrap(tiles: Set<Pair<Int, Int>>, walls: Set<Pair<Int, Int>>, state: State): State {
return State(when (state.facing) {
0 -> (tiles + walls).filter { it.second == state.coord.second }.minByOrNull { it.first }!!
1 -> (tiles + walls).filter { it.first == state.coord.first }.minByOrNull { it.second }!!
2 -> (tiles + walls).filter { it.second == state.coord.second }.maxByOrNull { it.first }!!
3 -> (tiles + walls).filter { it.first == state.coord.first }.maxByOrNull { it.second }!!
else -> throw IllegalStateException()
}, state.facing
)
}
private fun cubeWrap(tiles: Set<Pair<Int, Int>>, walls: Set<Pair<Int, Int>>, state: State): State {
return when (state.facing) {
0 -> {
when (state.coord.second) {
in 1..50 -> {
State((tiles + walls).filter { it.second == 151 - state.coord.second }.maxByOrNull { it.first }!!, 2)
}
in 51..100 -> {
State((tiles + walls).filter { it.first == 50 + state.coord.second }.maxByOrNull { it.second }!!, 3)
}
in 101..150 -> {
State((tiles + walls).filter { it.second == 151 - state.coord.second }.maxByOrNull { it.first }!!, 2)
}
else -> {
State((tiles + walls).filter { it.first == state.coord.second - 100 }.maxByOrNull { it.second }!!, 3)
}
}
}
1 -> {
when (state.coord.first) {
in 1..50 -> {
State((tiles + walls).filter { it.first == 100 + state.coord.first }.minByOrNull { it.second }!!, 1)
}
in 51..100 -> {
State((tiles + walls).filter { it.second == 100 + state.coord.first }.maxByOrNull { it.first }!!, 2)
}
else -> {
State((tiles + walls).filter { it.second == state.coord.first - 50 }.maxByOrNull { it.first }!!, 2)
}
}
}
2 -> {
when (state.coord.second) {
in 1..50 -> {
State((tiles + walls).filter { it.second == 151 - state.coord.second }.minByOrNull { it.first }!!, 0)
}
in 51..100 -> {
State((tiles + walls).filter { it.first == state.coord.second - 50 }.minByOrNull { it.second }!!, 1)
}
in 101..150 -> {
State((tiles + walls).filter { it.second == 151 - state.coord.second }.minByOrNull { it.first }!!, 0)
}
else -> {
State((tiles + walls).filter { it.first == state.coord.second - 100 }.minByOrNull { it.second }!!, 1)
}
}
}
3 -> {
when (state.coord.first) {
in 1..50 -> {
State((tiles + walls).filter { it.second == 50 + state.coord.first }.minByOrNull { it.first }!!, 0)
}
in 51..100 -> {
State((tiles + walls).filter { it.second == 100 + state.coord.first }.minByOrNull { it.first }!!, 0)
}
else -> {
State((tiles + walls).filter { it.first == state.coord.first - 100 }.maxByOrNull { it.second }!!, 3)
}
}
}
else -> throw IllegalStateException()
}
} | 0 | Kotlin | 0 | 0 | 0e0cae3b9a97c6019c219563621b43b0eb0fc9db | 5,790 | advent-of-code-2022 | MIT License |
src/main/kotlin/aoc2021/day9/SmokeBasin.kt | arnab | 75,525,311 | false | null | package aoc2021.day9
import java.util.LinkedList
object SmokeBasin {
data class Loc(val x: Int, val y: Int)
fun parse(data: String) = data.split("\n")
.foldIndexed(mutableMapOf()) { row, heights: MutableMap<Loc, Int>, line ->
line.split("").filter { it.isNotBlank() } .foldIndexed(heights) { col, heights, height ->
heights[Loc(col, row)] = height.toInt()
heights
}
}
fun calculateRiskScore(heightByLoc: Map<Loc, Int>) = findLowPoints(heightByLoc).values.sumBy { it + 1 }
private fun findLowPoints(heightByLoc: Map<Loc, Int>): Map<Loc, Int> = heightByLoc.filter {
findAdjacents(it.key).filter { adjacent -> heightByLoc.containsKey(adjacent) }
.all { adjacent -> it.value < heightByLoc[adjacent]!! }
}
private fun findAdjacents(loc: Loc) = listOf(
Loc(loc.x - 1, loc.y),
Loc(loc.x + 1, loc.y),
Loc(loc.x, loc.y - 1),
Loc(loc.x, loc.y + 1),
)
fun calculateLargeBasinsScore(heightByLoc: Map<Loc, Int>) = findLowPoints(heightByLoc).keys.asSequence()
.map { findBasinAround(it, heightByLoc) }
.map { it.size }
.sortedByDescending { it }
.take(3)
.fold(1) { score, basinSize -> score * basinSize }
private fun findBasinAround(start: Loc, heightByLoc: Map<Loc, Int>): Set<Loc> {
val basin = HashSet<Loc>()
val candidates = LinkedList(findAdjacents(start)
.filter { adjacent -> heightByLoc.containsKey(adjacent) }
.filter { heightByLoc[it]!! < 9 })
while (candidates.isNotEmpty()) {
val nextLoc = candidates.pop()
if (heightByLoc[nextLoc]!! < 9) {
basin.add(nextLoc)
val secondDegreeAdjacents = findAdjacents(nextLoc)
.filter { adjacent -> heightByLoc.containsKey(adjacent) }
.filter { heightByLoc[it]!! < 9 }
.filter { !basin.contains(it) }
candidates.addAll(secondDegreeAdjacents)
}
}
return basin
}
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 2,120 | adventofcode | MIT License |
src/Day13.kt | Shykial | 572,927,053 | false | {"Kotlin": 29698} | fun main() {
fun part1(input: List<String>) = input
.chunkedBy { it.isBlank() }
.map { (first, second) ->
DataPacketPair(
parsePacketLine(first),
parsePacketLine(second)
)
}.foldIndexed(0) { index, acc, (first, second) ->
if (arePacketsInTheRightOrder(first, second)) acc + index + 1 else acc
}
fun part2(input: List<String>): Int {
val firstExtraPacket = listOf(ListUnit(listOf(IntUnit(2))))
val secondExtraPacket = listOf(ListUnit(listOf(IntUnit(6))))
val sortedPackets = input
.filter { it.isNotBlank() }
.map(::parsePacketLine)
.plus(sequenceOf(firstExtraPacket, secondExtraPacket))
.sortedWith { o1, o2 ->
when {
o1 == o2 -> 0
arePacketsInTheRightOrder(o1, o2) -> -1
else -> 1
}
}
return (sortedPackets.indexOf(firstExtraPacket) + 1) * (sortedPackets.indexOf(secondExtraPacket) + 1)
}
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private fun arePacketsInTheRightOrder(first: List<PacketUnit>, second: List<PacketUnit>): Boolean {
first.zip(second).forEach { (firstUnit, secondUnit) ->
when (firstUnit) {
is IntUnit -> when (secondUnit) {
is IntUnit -> if (firstUnit.value != secondUnit.value) return firstUnit.value < secondUnit.value
is ListUnit -> if (listOf(firstUnit) != secondUnit.values)
return arePacketsInTheRightOrder(listOf(firstUnit), secondUnit.values)
}
is ListUnit -> when (secondUnit) {
is IntUnit -> if (firstUnit.values != listOf(secondUnit))
return arePacketsInTheRightOrder(firstUnit.values, listOf(secondUnit))
is ListUnit -> if (firstUnit != secondUnit)
return arePacketsInTheRightOrder(firstUnit.values, secondUnit.values)
}
}
}
return first.size <= second.size
}
private fun parsePacketLine(packetLine: String): List<PacketUnit> {
val rootNode = ListPacketNode()
var currentListPacketNode = rootNode
val digitBuilder = StringBuilder()
packetLine.substring(1).forEach { char ->
if (char in '0'..'9') digitBuilder.append(char)
else {
if (digitBuilder.isNotEmpty()) currentListPacketNode.value += IntUnit(digitBuilder.toString().toInt())
digitBuilder.clear()
when (char) {
'[' -> {
ListPacketNode(upperNode = currentListPacketNode)
val listPacketNode = ListPacketNode(upperNode = currentListPacketNode)
currentListPacketNode.value += ListUnit(listPacketNode.value)
currentListPacketNode = listPacketNode
}
']' -> if (currentListPacketNode != rootNode) currentListPacketNode = currentListPacketNode.upperNode!!
}
}
}
return rootNode.value
}
private data class ListPacketNode(
val value: MutableList<PacketUnit> = mutableListOf(),
val upperNode: ListPacketNode? = null
)
private sealed interface PacketUnit
@JvmInline
private value class IntUnit(val value: Int) : PacketUnit
@JvmInline
private value class ListUnit(val values: List<PacketUnit>) : PacketUnit
private data class DataPacketPair(
val firstPacket: List<PacketUnit>,
val secondPacket: List<PacketUnit>
) | 0 | Kotlin | 0 | 0 | afa053c1753a58e2437f3fb019ad3532cb83b92e | 3,580 | advent-of-code-2022 | Apache License 2.0 |
src/Day2.kt | sitamshrijal | 574,036,004 | false | {"Kotlin": 34366} | fun main() {
fun parse(input: List<String>): List<Game> = input.map {
Game(Move.parse(it[0]), Move.parse(it[2]))
}
fun part1(input: List<String>): Int {
val games = parse(input)
return games.sumOf { it.score() }
}
fun part2(input: List<String>): Int {
val games = parse(input)
val mapped = games.map {
val (opponent, you) = it
var choice = Move.ROCK
// Loss
if (you == Move.ROCK) {
choice = when (opponent) {
Move.ROCK -> Move.SCISSORS
Move.PAPER -> Move.ROCK
Move.SCISSORS -> Move.PAPER
}
}
// Draw
if (you == Move.PAPER) {
choice = opponent
}
// Win
if (you == Move.SCISSORS) {
choice = when (opponent) {
Move.ROCK -> Move.PAPER
Move.PAPER -> Move.SCISSORS
Move.SCISSORS -> Move.ROCK
}
}
Game(opponent, choice)
}
return mapped.sumOf { it.score() }
}
val input = readInput("input2")
println(part1(input))
println(part2(input))
}
enum class Move(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
companion object {
fun parse(char: Char): Move = when (char) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> error("Invalid char!")
}
}
}
data class Game(val opponent: Move, val you: Move) {
private fun isDraw(): Boolean = opponent == you
private fun isWin(): Boolean = when (opponent) {
Move.ROCK -> you == Move.PAPER
Move.PAPER -> you == Move.SCISSORS
Move.SCISSORS -> you == Move.ROCK
}
fun score(): Int {
var score = you.score
if (isDraw()) {
score += 3
}
if (isWin()) {
score += 6
}
return score
}
}
| 0 | Kotlin | 0 | 0 | fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d | 2,056 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc/year2021/Day03.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2021
import aoc.Puzzle
import aoc.year2021.Day03.Criteria.LEAST_COMMON
import aoc.year2021.Day03.Criteria.MOST_COMMON
/**
* [Day 3 - Advent of Code 2021](https://adventofcode.com/2021/day/3)
*/
object Day03 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int {
val lines = input.lines()
val bitCounts = IntArray(lines.first().length) { 0 }
lines.forEach { line ->
line.forEachIndexed { i, c ->
when (c) {
'0' -> bitCounts[i] -= 1
'1' -> bitCounts[i] += 1
}
}
}
val gammaRate = bitCounts.fold(0) { acc, i -> (acc shl 1) or (if (i > 0) 1 else 0) }
val epsilonRate = gammaRate.inv() and ((1 shl bitCounts.size) - 1)
return gammaRate * epsilonRate
}
override fun solvePartTwo(input: String): Int {
val values: List<IntArray> = input.lines().map { line -> line.map { it.digitToInt() }.toIntArray() }
val o2Rate = findRating(values, MOST_COMMON)
val co2Rate = findRating(values, LEAST_COMMON)
return o2Rate * co2Rate
}
private fun findRating(values: List<IntArray>, criteria: Criteria): Int {
generateSequence(0) { it + 1 }.fold(values) { acc, i ->
if (acc.size == 1)
return acc.single()
.fold(0) { int, bit -> (int shl 1) or bit }
acc.groupBy { it[i] }.let {
val size0 = it.getValue(0).size
val size1 = it.getValue(1).size
if (size0 <= size1) when (criteria) {
MOST_COMMON -> it.getValue(1)
LEAST_COMMON -> it.getValue(0)
} else when (criteria) {
MOST_COMMON -> it.getValue(0)
LEAST_COMMON -> it.getValue(1)
}
}
}
throw IllegalStateException()
}
private enum class Criteria {
MOST_COMMON,
LEAST_COMMON
}
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 2,034 | advent-of-code | Apache License 2.0 |
src/Day13.kt | pimtegelaar | 572,939,409 | false | {"Kotlin": 24985} | import Packet.PacketInteger
import Packet.PacketList
sealed class Packet : Comparable<Packet> {
data class PacketList(val value: List<Packet>) : Packet() {
override fun compareTo(other: Packet): Int = when (other) {
is PacketInteger -> compareTo(PacketList(listOf(other)))
is PacketList -> {
value.zip(other.value) { left, right -> left compareTo right }.forEach { if (it != 0) return it }
value.size - other.value.size
}
}
}
data class PacketInteger(val value: Int) : Packet() {
override fun compareTo(other: Packet) = when (other) {
is PacketInteger -> value.compareTo(other.value)
is PacketList -> PacketList(listOf(this)).compareTo(other)
}
}
}
fun main() {
fun String.toPacket(): Packet {
if (isEmpty()) {
return PacketList(emptyList())
}
if (length == 1) {
return PacketInteger(toInt())
}
var braceCount = 0
val packets = mutableListOf<Packet>()
var subPacketStart = 0
for (i in 0 until length) {
val current = this[i]
if (current == ',') {
continue
}
if (current == '[') {
braceCount++
if (subPacketStart == 0) {
subPacketStart = i + 1
}
continue
}
if (braceCount == 0) {
packets.add(PacketInteger(current.toString().toInt()))
continue
}
if (current == ']') {
braceCount--
if (braceCount == 0) {
packets.add(substring(subPacketStart..i - 1).toPacket())
subPacketStart = 0
}
}
}
return PacketList(packets)
}
fun String.dropOuter() = drop(1).dropLast(1)
fun part1(input: List<String>): Int {
val pairs = input.chunked(3).map { Pair(it[0].dropOuter().toPacket(), it[1].dropOuter().toPacket()) }
return pairs.map { (left, right) -> left <= right }.withIndex().filter { it.value }.sumOf { it.index + 1 }
}
fun part2(input: List<String>): Int {
val divider2 = "[[2]]".toPacket()
val divider6 = "[[6]]".toPacket()
val sorted = input.asSequence()
.filter { it.isNotBlank() }
.map { it.toPacket() }
.plus(divider2).plus(divider6)
.sorted()
.toList()
return (sorted.indexOf(divider2) + 1) * (sorted.indexOf(divider6) + 1)
}
val testInput = readInput("Day13_test")
val input = readInput("Day13")
val part1 = part1(testInput)
check(part1 == 13) { part1 }
println(part1(input))
val part2 = part2(testInput)
check(part2 == 140) { part2 }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16ac3580cafa74140530667413900640b80dcf35 | 2,905 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day10.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2022
fun main() {
fun List<String>.toInstructionValuePairs() = asSequence()
.map { it.split(" ") }
.map { (it[0] to it.getOrNull(1)?.run { toInt() }) }
.map { if (it.first == "addx") listOf(it, "noop" to null) else listOf(it) }
.flatten()
fun part1(input: List<String>): Int =
input.toInstructionValuePairs()
.let {
it.plus("noop" to null).plus("noop" to null)
.zip(listOf("noop" to null).plus(it).asSequence())
.zip(listOf("noop" to null, "noop" to null).plus(it).asSequence())
.mapIndexed { index, pair -> (pair.second.second ?: 0) to index + 1 }
.runningFold(1 to 1) { (x, _), (instructionValue, cycleIndex) ->
(x + instructionValue) to cycleIndex
}
.filter { it.second in listOf(20, 60, 100, 140, 180, 220) }
.map { it.first * it.second }
.sum()
}
fun part2(input: List<String>): String =
input.toInstructionValuePairs()
.mapIndexed { index, pair -> (pair.second ?: 0) to index + 1 }
.runningFold(1 to 0) { acc, pair -> (acc.first + pair.first) to pair.second }
.fold(mutableListOf<String>() to 0) { (row, spritePos), (x, pos) ->
(if ((pos % 40) in (spritePos - 1..spritePos + 1)) "#" else ".").let { row.add(it) }
row to x
}
.first
.dropLast(1)
.chunked(40)
.joinToString("\n") {
it.joinToString("")
}
val testInput = readInputLines("Day10_test")
check(part1(testInput) == 13140)
val testOutputPart2 = readInput("Day10_test2")
check(part2(testInput) == testOutputPart2)
val input = readInputLines("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 1,974 | advent-of-code | Apache License 2.0 |
src/Day18.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | fun main() {
val testInput = readInput("Day18_test")
.map(String::toCoordinates)
val input = readInput("Day18")
.map(String::toCoordinates)
part1(testInput).also {
println("Part 1, test input: $it")
check(it == 64)
}
part1(input).also {
println("Part 1, real input: $it")
// check(it == 3576)
}
part2(testInput).also {
println("Part 2, test input: $it")
check(it == 58)
}
part2(input).also {
println("Part 2, real input: $it")
// check(it == 2066)
}
}
private fun part1(input: List<Xyz>): Int {
val set = input.toSet()
return input.sumOf { (x, y, z) ->
directions.map { (dx, dy, dz) ->
Xyz(x = x + dx, y = y + dy, z = z + dz)
}.count {
it !in set
}
}
}
enum class OneSideStatus {
BLOCKED, OPEN
}
private fun part2(input: List<Xyz>): Int {
val open = mutableSetOf<Xyz>()
val blocksSet = input.toSet()
val xRange = input.minOf { it.x }..input.maxOf { it.x }
val yRange = input.minOf { it.y }..input.maxOf { it.y }
val zRange = input.minOf { it.z }..input.maxOf { it.z }
fun getStatus(b: Xyz, d: XyzDirection): OneSideStatus {
var (xx, yy, zz) = listOf(b.x + d.dx, b.y + d.dy, b.z + d.dz)
while (xx in xRange && yy in yRange && zz in zRange) {
val p = Xyz(xx, yy, zz)
if (p in blocksSet) {
return OneSideStatus.BLOCKED
}
if (p in open) {
return OneSideStatus.OPEN
}
xx += d.dx
yy += d.dy
zz += d.dz
}
return OneSideStatus.OPEN
}
// Прокатило. Тут должен быть BFS, по идее
repeat(2) {
for (z in zRange.first - 1..zRange.last + 1) {
for (y in yRange.first - 1..yRange.last + 1) {
for (x in xRange.first - 1..xRange.last + 1) {
val p = Xyz(x, y, z)
if (p in blocksSet || p in open) continue
val status = directions.map { d -> getStatus(p, d) }
if (status.any { it == OneSideStatus.OPEN }) {
open += p
}
}
}
}
}
return input.sumOf { xyz ->
directions.map { (dx, dy, dz) ->
xyz.copy(x = xyz.x + dx, y = xyz.y + dy, z = xyz.z + dz)
}.count {
it in open
}
}
}
private data class Xyz(val x: Int, val y: Int, val z: Int)
private data class XyzDirection(val dx: Int = 0, val dy: Int = 0, val dz: Int = 0)
private val directions = listOf(
XyzDirection(dx = -1),
XyzDirection(dx = 1),
XyzDirection(dy = -1),
XyzDirection(dy = 1),
XyzDirection(dz = -1),
XyzDirection(dz = 1),
)
private fun String.toCoordinates(): Xyz {
return this.split(",").let { (x, y, z) ->
Xyz(x.toInt(), y.toInt(), z.toInt())
}
} | 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 3,003 | aoc22-kotlin | Apache License 2.0 |
src/Day02.kt | Venkat-juju | 572,834,602 | false | {"Kotlin": 27944} | fun main() {
fun getScoreOfSelection(selection: String): Int {
return when(selection) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
}
fun getScore(choices: String): Int {
// A - Rock, B - Paper, C - Scissors
// X - Rock, Y - Paper, Z - Scissors
// Rock wins Scissors, Scissors defeats Paper, Paper defeats Rock
val opponentChoice = choices.split(" ").first()
val myChoice = choices.split(" ").last()
val isWin = (opponentChoice == "C" && myChoice == "X") || (opponentChoice == "A" && myChoice == "Y") || (opponentChoice == "B" && myChoice == "Z")
val isDraw = (opponentChoice == "C" && myChoice == "Z") || (opponentChoice == "B" && myChoice == "Y") || (opponentChoice == "A" && myChoice == "X")
return (if (isWin) 6 else if (isDraw) 3 else 0) + getScoreOfSelection(myChoice)
}
fun getMyChoice(opponentChoice: String, resultHasToBe: String): String {
val needWin = resultHasToBe == "Z"
val needDraw = resultHasToBe == "Y"
return when(opponentChoice) {
"A" -> {
if (needWin) "Y" else if (needDraw) "X" else "Z"
}
"B" -> {
if (needWin) "Z" else if (needDraw) "Y" else "X"
}
"C" -> {
if (needWin) "X" else if (needDraw) "Z" else "Y"
}
else -> ""
}
}
fun part1(input: List<String>): Int {
var totalScore = 0
input.forEach {
totalScore += getScore(it)
}
return totalScore
}
fun part2(input: List<String>): Int {
var totalScore = 0
input.forEach {
val opponentChoice = it.split(" ").first()
val myChoice = getMyChoice(opponentChoice, it.split(" ").last())
totalScore += getScore("$opponentChoice $myChoice")
}
return totalScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println(part2(testInput))
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 785a737b3dd0d2259ccdcc7de1bb705e302b298f | 2,250 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | fun main() {
val f = readInput("Day04")
fun parseLine(line: String): List<IntRange> {
return line.split(',')
.map { it.split('-').map { it.toInt() }.let { (x, y) -> x..y } }
}
fun part1(input: List<String>): Int {
return input
.map(::parseLine)
.count { (x, y) -> x.contains(y) || y.contains(x) }
}
fun part2(input: List<String>): Int {
return input
.map(::parseLine)
.count { (x, y) -> x.overlaps(y) }
}
val testF = readInput("Day04_test")
check(part1(testF) == 2)
check(part2(testF) == 4)
println("Part 1")
println(part1(f))
println("Part 2")
println(part2(f))
}
/* returns whether a range contains other range as "subrange". Example:
* <------------> A
* <--------> subrange of A
* <-------> not subrange of A
* <---------------------> not subrange of A, and A is subrange of this
*/
fun IntRange.contains(other: IntRange): Boolean = other.first in this && other.last in this
fun IntRange.overlaps(other: IntRange): Boolean = other.first in this || other.last in this || other.contains(this)
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 1,206 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/_2021/Day5.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2021
import aoc
import parseInput
import range
import java.util.regex.Pattern
private val REGEX = Pattern.compile("(\\d+),(\\d+) -> (\\d+),(\\d+)")
fun main() {
aoc(2021, 5) {
aocRun {
countOverlappingPoints(it, true)
}
aocRun {
countOverlappingPoints(it, false)
}
}
}
private fun parseLines(input: String): List<Line> = parseInput(REGEX, input) {
Line(it.group(1).toInt() to it.group(2).toInt(), it.group(3).toInt() to it.group(4).toInt())
}
private fun countOverlappingPoints(input: String, horizontalOrVerticalOnly: Boolean): Int {
val posCounts = mutableMapOf<Pair<Int, Int>, Int>()
parseLines(input)
.let { lines -> if (horizontalOrVerticalOnly) lines.filter { it.isHorizontalOrVertical } else lines }
.map { it.getAllPositions(horizontalOrVerticalOnly) }
.forEach { positions ->
positions.forEach { posCounts.compute(it) { _, v -> if (v == null) 1 else v + 1 } }
}
return posCounts.values.count { it >= 2 }
}
private class Line(val pos1: Pair<Int, Int>, val pos2: Pair<Int, Int>) {
private val diffX: Int = pos1.first.compareTo(pos2.first)
private val diffY: Int = pos1.second.compareTo(pos2.second)
val isHorizontalOrVertical: Boolean
get() = (diffX == 0 || diffY == 0) && diffX != diffY
fun getAllPositions(horizontalOrVerticalOnly: Boolean): List<Pair<Int, Int>> = when {
isHorizontalOrVertical -> {
when {
diffX != 0 -> {
val y = pos1.second
range(pos1.first, pos2.first).map { it to y }
}
diffY != 0 -> {
val x = pos1.first
range(pos1.second, pos2.second).map { x to it }
}
else -> emptyList()
}
}
!horizontalOrVerticalOnly -> {
val rangeX = range(pos1.first, pos2.first)
val rangeY = range(pos1.second, pos2.second)
rangeX.zip(rangeY)
}
else -> emptyList()
}
override fun toString(): String = "${pos1.first},${pos1.second} -> ${pos2.first},${pos2.second}"
}
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 1,891 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/day04/Day04.kt | mherda64 | 512,106,270 | false | {"Kotlin": 10058} | package day04
import readInput
fun main() {
fun processInput(input: List<String>): Pair<List<Int>, List<BingoBoard>> {
val draws = input.first().split(",").map { it.toInt() }
val boards = input.drop(1).chunked(6).map { board ->
board.filter { it.isNotBlank() }.map { line ->
line.trim()
.split(Regex("\\W+"))
.map { it.toInt() }
}
}.map { BingoBoard.fromCollection(it) }
return Pair(draws, boards)
}
fun part1(input: List<String>): Int {
val (draws, boards) = processInput(input)
for (draw in draws) {
for (board in boards) {
board.markNumber(draw)
if (board.isWinner()) {
return board.unmarkedSum() * draw
}
}
}
return 0
}
fun part2(input: List<String>): Int {
val (draws, boards) = processInput(input)
var winCounter = 0
for (draw in draws) {
for (board in boards) {
if (!board.isWinner()) {
board.markNumber(draw)
if (board.isWinner()) {
winCounter++
if (winCounter == boards.size)
return board.unmarkedSum() * draw
}
}
}
}
return 0
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 4512)
check(part2(testInput) == 1924)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
class BingoBoard(val fields: List<List<Field>>) {
companion object {
fun fromCollection(input: Collection<Collection<Int>>): BingoBoard {
return BingoBoard(input.map { row -> row.map { elem -> Field(elem) }.toMutableList() })
}
}
fun markNumber(number: Int) {
for (row in fields) {
row.map {
if (it.value == number) it.mark()
}
}
}
fun isWinner(): Boolean {
return checkRows() || checkColumns()
}
fun unmarkedSum(): Int {
return fields.flatten().filterNot { it.marked }.sumOf { it.value }
}
private fun checkRows(): Boolean = fields.any { row -> row.all { it.marked } }
private fun checkColumns(): Boolean {
return fields.any { row ->
List(row.size) { index -> index }.any { column ->
(0..4).all { fields[it][column].marked }
}
}
}
}
class Field(val value: Int, var marked: Boolean = false) {
fun mark() {
marked = true
}
} | 0 | Kotlin | 0 | 0 | d04e179f30ad6468b489d2f094d6973b3556de1d | 2,690 | AoC2021_kotlin | Apache License 2.0 |
src/Day11.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Long {
val monkeys = parseMonkeys(input)
repeat(20) {
for (monkey in monkeys) {
monkey.takeTurn(monkeys) { it / 3 }
}
}
return monkeys.map { it.inspectedItems }.sorted().takeLast(2).reduce { acc, i -> acc * i }
}
fun part2(input: List<String>): Long {
val monkeys = parseMonkeys(input)
val divisor = calculateDivisor(input)
repeat(10_000) {
for (monkey in monkeys) {
// use modulo to keep relief levels manageable. chosen divisor to be a number which is
// divisible by all test divisors, to keep outcome of test same as if modulo was not
// applied. this way item gets thrown to same monkey as if modulo where not applied and
// therefore the inspected items per monkey is the same as if modulo was not used
monkey.takeTurn(monkeys) { it % divisor }
}
}
return monkeys.map { it.inspectedItems }.sorted().takeLast(2).reduce { acc, i -> acc * i }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
assertEquals(10605L, part1(testInput))
assertEquals(2713310158L, part2(testInput))
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
private fun parseMonkeys(input: List<String>): List<Monkey> {
return input.chunked(7).map {
val startingItemsInput = it[1]
val operationInput = it[2]
val testInput = it.slice(3..5)
Monkey(
parseStartingItems(startingItemsInput),
parseOperation(operationInput),
parseWorryLevelTester(testInput),
)
}
}
private fun calculateDivisor(input: List<String>): Long =
input.chunked(7).map { it[3].trim().split(" ").last().toLong() }.reduce { acc, l -> acc * l }
private class Monkey(
val items: MutableList<WorryLevel>,
val operation: Operation,
val test: WorryLevelTester
) {
var inspectedItems: Long = 0
private set
fun takeTurn(monkeys: List<Monkey>, reliefReduction: Operation) {
for (item in items) {
inspectedItems++
val newWorryLevel = reliefReduction(operation(item))
val target = test(newWorryLevel)
monkeys[target].items.add(newWorryLevel)
}
items.clear()
}
}
fun parseStartingItems(input: String): MutableList<WorryLevel> {
require(input.trim().startsWith("Starting items:"))
return input
.trim()
.removePrefix("Starting items: ")
.split(", ")
.map { it.toLong() }
.toMutableList()
}
fun parseOperation(input: String): Operation {
require(input.trim().startsWith("Operation:"))
val expression = input.split("=").last().trim()
val (leftRaw, operatorRaw, rightRaw) = expression.split(" ")
return { old ->
val left =
when (leftRaw) {
"old" -> old
else -> leftRaw.toLong()
}
val right =
when (rightRaw) {
"old" -> old
else -> rightRaw.toLong()
}
when (operatorRaw) {
"+" -> left + right
"-" -> left - right
"*" -> left * right
"/" -> left / right
else -> error("unknown operator, should not happen")
}
}
}
fun parseWorryLevelTester(input: List<String>): WorryLevelTester {
require(input.size == 3)
require(input[0].trim().startsWith("Test:"))
require(input[1].trim().startsWith("If true:"))
require(input[2].trim().startsWith("If false:"))
val divisor = input[0].split(" ").last().toLong()
val targetMonkeyIfTrue = input[1].split(" ").last().toInt()
val targetMonkeyIfFalse = input[2].split(" ").last().toInt()
return { worryLevel ->
if (worryLevel % divisor == 0L) {
targetMonkeyIfTrue
} else {
targetMonkeyIfFalse
}
}
}
typealias WorryLevel = Long
typealias Operation = (old: WorryLevel) -> WorryLevel
typealias WorryLevelTester = (worryLevel: WorryLevel) -> Int
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 3,924 | aoc2022 | Apache License 2.0 |
src/Day04.kt | stcastle | 573,145,217 | false | {"Kotlin": 24899} | fun getIntRanges(input: List<String>): Pair<List<IntRange>, List<IntRange>> {
val first: MutableList<IntRange> = mutableListOf()
val second: MutableList<IntRange> = mutableListOf()
input.forEach { line ->
val ranges: List<String> = line.split(',')
require(ranges.size == 2)
val firstRange: List<String> = ranges.first().split('-')
first.add(IntRange(firstRange.first().toInt(), firstRange.last().toInt()))
val secondRange = ranges.last().split('-')
second.add(IntRange(secondRange.first().toInt(), secondRange.last().toInt()))
}
return Pair(first, second)
}
fun main() {
fun part1(input: List<String>): Int {
val (first, second) = getIntRanges(input)
return first.zip(second).count {
it.first.all { elementInFirst -> it.second.contains(elementInFirst) } ||
it.second.all { elementInSecond -> it.first.contains(elementInSecond) }
}
}
fun part2(input: List<String>): Int {
val (first, second) = getIntRanges(input)
return first.zip(second).count {
it.first.any { elementInFirst -> it.second.contains(elementInFirst) } ||
it.second.any { elementInSecond -> it.first.contains(elementInSecond) }
}
}
val day = "04"
val testInput = readInput("Day${day}_test")
println("Part 1 test = ${part1(testInput)}")
val input = readInput("Day${day}")
println("part1 = ${part1(input)}")
println("Part 2 test = ${part2(testInput)}")
println("part2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 746809a72ea9262c6347f7bc8942924f179438d5 | 1,470 | aoc2022 | Apache License 2.0 |
src/Day07.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | fun main() {
data class Node(val name: String, var size: Int = 0, val dir: Boolean = false, val parent: Node? = null) {
fun propagateSize() {
var curr = parent
while (curr != null) {
curr.size += size
curr = curr.parent
}
}
}
data class Common(val input: List<String>) {
val nodes = mutableListOf<Node>()
val root = Node(name = "/")
init {
var currentDir = root
input
.map { it.split(" ") }
.forEach {
val (first, second) = it
if (first == "$" && second == "cd") {
when (val dirName = it[2]) {
".." -> currentDir = currentDir.parent!!
"/" -> currentDir = root
else -> {
currentDir = Node(name = dirName, dir = true, parent = currentDir)
nodes.add(currentDir)
}
}
} else if (first.isNumber()) {
nodes.add(Node(name = second, size = first.toInt(), parent = currentDir))
}
}
nodes.filterNot { it.dir }
.forEach { it.propagateSize() }
}
}
fun part1(input: List<String>): Int {
val common = Common(input)
return common.nodes
.filter { it.dir && it.size <= 100000 }
.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val common = Common(input)
val freeSpace = 70000000 - common.root.size
return common.nodes
.filter { it.dir }
.fold(70000000) { acc, item ->
if (freeSpace + item.size >= 30000000 && acc > item.size) {
item.size
} else {
acc
}
}
}
val input = readInput("inputs/Day07")
println(part1(input))
println(part2(input))
}
private fun String.isNumber(): Boolean {
return toIntOrNull() != null
}
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 2,195 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | buongarzoni | 572,991,996 | false | {"Kotlin": 26251} | fun solveDay04() {
val values = readInput("Day04")
.map { line -> line.split("-", ",").map { it.toInt() } }
val part1 = values.count { (a, b, c, d) -> (a <= c && b >= d) || (a >= c && b <= d) }
println(part1)
val part2 = values.count { (a, b, c, d) -> a <= d && b >= c }
println(part2)
val myPart1 = readInput("Day04")
.count {
val (firstRange, secondRange) = it.getRanges()
firstRange in secondRange || secondRange in firstRange
}
println(myPart1)
val myPart2 = readInput("Day04")
.count {
val (firstRange, secondRange) = it.getRanges()
firstRange overlaps secondRange
}
println(myPart2)
}
private operator fun IntRange.contains(other: IntRange) = first in other && last in other
private infix fun IntRange.overlaps(other: IntRange) =
first in other || last in other || other.first in this || other.last in this
private val String.lowLimit get(): Int = substringBefore('-').toInt()
private val String.upperLimit get(): Int = substringAfter('-').toInt()
private fun String.getRanges() = split(',').map { it.range() }
private fun String.range() = lowLimit..upperLimit
| 0 | Kotlin | 0 | 0 | 96aadef37d79bcd9880dbc540e36984fb0f83ce0 | 1,199 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch9/Problem98.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch9
import dev.bogwalk.util.combinatorics.permutationID
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Problem 98: Anagramic Squares
*
* https://projecteuler.net/problem=98
*
* Goal: Find all square numbers with N digits that have at least 1 anagram that is also a square
* number with N digits. Use this set to either map squares to anagram strings or to find the
* largest square with the most anagramic squares in the set.
*
* Constraints: 3 <= N <= 13
*
* e.g.: N = 4
* only 1 set of anagramic squares is of length > 2 -> {1296, 2916, 9216}
* largest = 9216
*/
class AnagramicSquares {
/**
* Project Euler specific implementation that requests the largest square number possible from
* any anagramic square pair found within a large list of words.
*
* e.g. CARE, when mapped to 1296 (36^2), forms a pair with its anagram RACE, which maps to
* one of the square's own anagrams, 9216 (96^2).
*
* @return Triple of Anagram word #1, Anagram word #2, the largest mapped square.
*/
fun findLargestAnagramicSquareByWords(words: List<String>): Triple<String, String, Int> {
val anagrams = findAnagrams(words)
var numOfDigits = Int.MAX_VALUE
var squares = emptyList<List<String>>()
var largest = Triple("", "", 0)
for (anagram in anagrams) {
if (anagram.first.length < numOfDigits) {
numOfDigits = anagram.first.length
squares = getEligibleSquares(numOfDigits)
}
for (squareSet in squares) {
nextSquare@for (square in squareSet) {
// ensure square can be mapped to first word without different chars using
// the same digit; e.g. CREATION should not map to 11323225
val mapping = mutableMapOf<Char, Char>()
for ((ch, digit) in anagram.first.zip(square)) {
if (ch in mapping.keys) {
if (mapping[ch] == digit) continue else continue@nextSquare
} else {
if (digit in mapping.values) continue@nextSquare else mapping[ch] = digit
}
}
val expected = anagram.second.map { mapping[it]!! }.joinToString("")
if (expected in squareSet) {
val largerSquare = maxOf(square.toInt(), expected.toInt())
if (largerSquare > largest.third) {
largest = Triple(anagram.first, anagram.second, largerSquare)
}
}
}
}
// only interested in the largest found from the first set of squares with a result
if (largest.first.isNotEmpty()) break
}
return largest
}
/**
* Returns all sets of anagrams found in a list of words, sorted in descending order by the
* length of the words.
*/
private fun findAnagrams(words: List<String>): List<Pair<String, String>> {
val permutations = mutableMapOf<String, List<String>>()
for (word in words) {
if (word.length <= 2) continue // palindromes are not anagrams
val permId = word.toList().sorted().joinToString("")
permutations[permId] = permutations.getOrDefault(permId, emptyList()) + word
}
val anagrams = mutableListOf<Pair<String, String>>()
for (permMatch in permutations.values) {
when (val count = permMatch.size) {
1 -> continue
2 -> anagrams.add(permMatch[0] to permMatch[1])
else -> { // only occurs once (size 3) from test resource, but let's be dynamic
for (i in 0 until count - 1) {
for (j in i + 1 until count) {
anagrams.add(permMatch[i] to permMatch[j])
}
}
}
}
}
return anagrams.sortedByDescending { it.first.length }
}
/**
* Returns all squares that have the desired number of digits and that are anagrams of other
* squares (based on their permutation id), with the latter being grouped together.
*
* Note that squares are found and returned in groups already sorted in ascending order.
*/
private fun getEligibleSquares(digits: Int): List<List<String>> {
val allSquares = mutableMapOf<String, List<String>>()
val maximum = 10.0.pow(digits).toLong()
var base = sqrt(10.0.pow(digits - 1)).toLong()
var square = base * base
while (square < maximum) {
val permId = permutationID(1L * square)
allSquares[permId] = allSquares.getOrDefault(permId, emptyList()) + square.toString()
base++
square = base * base
}
return allSquares.values.filter { it.size > 1 }
}
/**
* HackerRank specific implementation that only requires that all possible anagram squares
* with [n] digits be found. From this list of sets, the largest square from the largest set
* must be returned; otherwise, return the largest square from all equivalently sized sets.
*/
fun findLargestAnagramicSquareByDigits(n: Int): Long {
val squares = getEligibleSquares(n)
var largestSize = 0
var largestSquare = 0L
for (squareSet in squares) {
if (squareSet.size > largestSize) {
largestSize = squareSet.size
largestSquare = squareSet.last().toLong()
continue
}
if (squareSet.size == largestSize) {
largestSquare = max(largestSquare, squareSet.last().toLong())
}
}
return largestSquare
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 5,942 | project-euler-kotlin | MIT License |
src/main/kotlin/com/chriswk/aoc/advent2021/Day9.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.Pos
import com.chriswk.aoc.util.report
class Day9 : AdventDay(2021, 9) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day9()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun parseInput(input: List<String>): Array<IntArray> {
return input.map { line -> line.map { it.digitToInt() }.toIntArray() }.toTypedArray()
}
fun findMinima(grid: Array<IntArray>): List<Point> {
val maxRow = grid.size
val maxCol = grid[0].size
return grid.flatMapIndexed { x, inner ->
inner.mapIndexed { y, height ->
Point(Pos(x, y), height)
}
}.filter { it.isMinimal(grid, maxRow, maxCol) }
}
fun computeBasins(minima: List<Point>, grid: Array<IntArray>): List<Set<Point>> {
val maxRow = grid.size
val maxCol = grid[0].size
return minima.map { basin(it, grid, maxRow, maxCol) }
}
fun basin(p: Point, grid: Array<IntArray>, maxRow: Int, maxCol: Int): Set<Point> {
return p.neighbours(grid, maxRow, maxCol).fold(setOf(p)) { points, point ->
points + if (point.height - p.height >= 1) { basin(point, grid, maxRow, maxCol) } else { emptySet() }
}
}
data class Point(val pos: Pos, val height: Int) {
val risk: Int = height + 1
fun isMinimal(grid: Array<IntArray>, maxRow: Int, maxCol: Int): Boolean {
val all = pos.cardinalNeighbours(maxRow, maxCol).map { Point(it, grid[it.x][it.y]) } + this
val sorted = all.sortedBy { it.height }
return sorted[0] == this && sorted[1].height > this.height
}
fun neighbours(grid: Array<IntArray>, maxRow: Int, maxCol: Int): List<Point> {
return pos.cardinalNeighbours(maxRow, maxCol).filter { neighbour -> grid[neighbour.x][neighbour.y] < 9 }
.map { n -> Point(n, grid[n.x][n.y]) }
}
}
val grid = parseInput(inputAsLines)
val minima = findMinima(grid)
fun part1(): Int {
return minima.sumOf { it.risk }
}
fun part2(): Int {
return computeBasins(minima, grid)
.sortedByDescending { it.size }
.take(3)
.fold(1) { acc, e -> acc * e.size }
}
fun Set<Int>.product() = this.fold(1) { acc, e -> acc * e }
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,527 | adventofcode | MIT License |
src/Day05.kt | wmichaelshirk | 573,031,182 | false | {"Kotlin": 19037} |
data class Instruction(val number: Int, val fromColumn: Int, val toColumn: Int)
fun main() {
fun part1(input: List<String>): String {
// build a map of the towers
val towers = input.takeWhile { it.isNotBlank() }.reversed()
.map { it
.windowed(3, 4, true)
.mapIndexed{ i, c -> i+1 to c[1]}
}
val towerMap = towers.take(1)
.flatMap { it.map { i -> i.first to mutableListOf<Char>() } }
.toMap().toMutableMap()
towers.drop(1).forEach { row ->
row.forEach { if (it.second.isLetter()) towerMap[it.first]?.add(it.second) }
}
// parse and execute the moves
input.takeLastWhile { it.isNotBlank() }
.map{ row ->
val firstSplit = row.split(" from ")
val number = firstSplit.first().drop(5).toInt()
val (fromColumn, toColumn) = firstSplit.last().split(" to ").map { it.toInt() }
Instruction(number, fromColumn, toColumn)
}.forEach {
val (num, from, to) = it
val movedStack = towerMap[from]?.takeLast(num)?.reversed()?.toMutableList() ?: mutableListOf()
towerMap[from] = towerMap[from]?.dropLast(num)?.toMutableList() ?: mutableListOf()
towerMap[to]?.addAll(movedStack)
}
return towerMap.values.map { it.last() }.joinToString("")
}
fun part2(input: List<String>): String {
// build a map of the towers
val towers = input.takeWhile { it.isNotBlank() }.reversed()
.map { it
.windowed(3, 4, true)
.mapIndexed{ i, c -> i+1 to c[1]}
}
val towerMap = towers.take(1)
.flatMap { it.map { i -> i.first to mutableListOf<Char>() } }
.toMap().toMutableMap()
towers.drop(1).forEach { row ->
row.forEach { if (it.second.isLetter()) towerMap[it.first]?.add(it.second) }
}
// parse and execute the moves
input.takeLastWhile { it.isNotBlank() }
.map{ row ->
val firstSplit = row.split(" from ")
val number = firstSplit.first().drop(5).toInt()
val (fromColumn, toColumn) = firstSplit.last().split(" to ").map { it.toInt() }
Instruction(number, fromColumn, toColumn)
}.forEach {
val (num, from, to) = it
val movedStack = towerMap[from]?.takeLast(num)?.toMutableList() ?: mutableListOf()
towerMap[from] = towerMap[from]?.dropLast(num)?.toMutableList() ?: mutableListOf()
towerMap[to]?.addAll(movedStack)
}
return towerMap.values.map { it.last() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | b748c43e9af05b9afc902d0005d3ba219be7ade2 | 3,078 | 2022-Advent-of-Code | Apache License 2.0 |
src/aoc2022/Day07.kt | nguyen-anthony | 572,781,123 | false | null | package aoc2022
import utils.readInputAsList
data class FileInfo(val fileSize: Int, val name: String, val isDirectory: Boolean)
fun main() {
fun parseDirectories(input: List<String>): Map<String, List<FileInfo>> {
var path = listOf("/")
val map = mutableMapOf<String, List<FileInfo>>()
for(terminalLine in input){
if (terminalLine == "$ cd /") {
path = listOf("/")
} else if (terminalLine == "$ cd ..") {
path = path.dropLast(1)
} else if (terminalLine.startsWith("$ cd")) {
val newDir = terminalLine.split(" ").last()
path = (path + newDir)
} else if (terminalLine == "$ ls") {
continue
} else if (terminalLine.startsWith("dir")) {
val pathString = path.joinToString("/")
val name = terminalLine.split(" ").last()
val file = FileInfo(0, name, true)
val currentList = map.getOrDefault(pathString, emptyList())
map[pathString] = currentList + file
} else {
val pathString = path.joinToString("/")
val (size, name) = terminalLine.split(" ")
val file = FileInfo(size.toInt(), name, false)
val currentList = map.getOrDefault(pathString, emptyList())
map[pathString] = currentList + file
}
}
return map
}
fun getSize(dirMap: Map<String, List<FileInfo>>, dir: String) : Int {
val files = dirMap.getValue(dir)
val fileSize = files.filter { !it.isDirectory }.sumOf { it.fileSize }
val subDirectories = files.filter { it.isDirectory }
return fileSize + subDirectories.sumOf { getSize(dirMap, dir + "/" + it.name) }
}
fun getSizes(dirMap: Map<String, List<FileInfo>>) : Map<String, Int> {
return dirMap.mapValues { entry -> getSize(dirMap, entry.key) }
}
fun part1(input: List<String>) : Any {
return getSizes(parseDirectories((input))).filter { it.value <= 100000 }.values.sum()
}
fun part2(input: List<String>) : Int {
return getSizes(parseDirectories(input)).values.filter { it > (30000000 - (70000000 - getSizes(parseDirectories(input)).getValue("/"))) }.min()
}
val input = readInputAsList("Day07", "2022")
println(part1(input))
println(part2(input))
val testInput = readInputAsList("Day07_test", "2022")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
} | 0 | Kotlin | 0 | 0 | 9336088f904e92d801d95abeb53396a2ff01166f | 2,566 | AOC-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/Day14.kt | cbrentharris | 712,962,396 | false | {"Kotlin": 171464} | import Day13.transpose
import kotlin.String
import kotlin.collections.List
object Day14 {
private const val ROUNDED = 'O'
fun part1(input: List<String>): String {
val transposedDish = transpose(input)
return transposedDish.sumOf { row ->
val rolled = roll(row)
rolled.reversed().withIndex().filter { (_, char) -> char == ROUNDED }.sumOf { (idx, _) -> idx + 1 }
}.toString()
}
private fun roll(row: String): String {
if (row.isBlank()) {
return row
}
if (row[0] == ROUNDED) {
return row[0] + roll(row.substring(1))
}
val indexToSwap = row.withIndex().dropWhile { (_, char) -> char == '.' }.firstOrNull()
if (indexToSwap == null) {
return row
}
val (idx, _) = indexToSwap
return if (row[idx] == ROUNDED) {
ROUNDED.toString() + roll(row.substring(1, idx) + "." + row.substring(idx + 1))
} else {
row.substring(0, idx + 1) + roll(row.substring(idx + 1))
}
}
fun part2(input: List<String>): String {
val cycled = cycleUntil(transpose(input), 1_000_000_000)
return cycled
.sumOf { row ->
val rowSum =
row.reversed().withIndex().filter { (_, char) -> char == ROUNDED }.sumOf { (idx, _) -> idx + 1 }
rowSum
}
.toString()
}
private fun cycleUntil(grid: List<String>, targetCycles: Int): List<String> {
val seenMap = mutableMapOf<List<String>, Long>()
var cycles = 0L
var cycled = cycle(grid)
while (cycles < targetCycles) {
cycled = cycle(cycled)
cycles++
if (seenMap.containsKey(cycled)) {
val firstSeen = seenMap[cycled]!!
val cyclesSince = cycles - firstSeen
var remainingCycles = (targetCycles - cycles) % cyclesSince - 1
while (remainingCycles > 0) {
cycled = cycle(cycled)
remainingCycles--
}
break
} else {
seenMap[cycled] = cycles
}
}
return cycled
}
private fun cycle(grid: List<String>): List<String> {
val northRoll = grid.map { roll(it) }
val west = transpose(northRoll)
val westRoll = west.map { roll(it) }
val south = transpose(westRoll).map { it.reversed() }
val southRoll = south.map { roll(it) }
val east = transpose(southRoll.map { it.reversed() }).map { it.reversed() }
val eastRoll = east.map { roll(it) }
val backNorth = transpose(eastRoll.map { it.reversed() })
return backNorth
}
}
| 0 | Kotlin | 0 | 1 | f689f8bbbf1a63fecf66e5e03b382becac5d0025 | 2,778 | kotlin-kringle | Apache License 2.0 |
src/day11/Code.kt | fcolasuonno | 572,734,674 | false | {"Kotlin": 63451, "Dockerfile": 1340} | package day11
import day06.main
import grouped
import readInput
data class Monkey(
var inspections: Long = 0L,
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: Long,
val nextMonkeyTrue: Int,
val nextMonkeyFalse: Int
) {
fun doBusiness(monkeys: List<Monkey>, relief: (Long) -> Long) {
inspections += items.size
items.forEach { item ->
val finalWorry = relief(operation(item))
val nextMonkey = if (finalWorry % test == 0L) nextMonkeyTrue else nextMonkeyFalse
monkeys[nextMonkey].items.add(finalWorry)
}
items.clear()
}
}
fun main() {
fun parseArgument(input: Long, operand: String) = when {
operand == "old" -> input
operand.toIntOrNull() != null -> operand.toLong()
else -> throw UnsupportedOperationException(operand)
}
fun parse(input: List<String>) = input.map { it.ifEmpty { null } }.grouped().map { lines ->
Monkey(
items = lines[1].substringAfter("Starting items: ").split("""\D+""".toRegex()).map(String::toLong)
.toMutableList(),
operation = lines[2].substringAfter("Operation: new = ").let {
val ops = it.split(" ")
when (ops[1]) {
"*" -> { worry -> parseArgument(worry, ops[0]) * parseArgument(worry, ops[2]) }
"+" -> { worry -> parseArgument(worry, ops[0]) + parseArgument(worry, ops[2]) }
else -> throw UnsupportedOperationException()
}
},
test = lines[3].substringAfter("Test: divisible by ").toLong(),
nextMonkeyTrue = lines[4].substringAfter("If true: throw to monkey ").toInt(),
nextMonkeyFalse = lines[5].substringAfter("If false: throw to monkey ").toInt()
)
}
fun List<Monkey>.keepAway(rounds: Int, relief: (Long) -> Long): Long {
repeat(rounds) {
forEach { monkey -> monkey.doBusiness(this, relief) }
}
return map(Monkey::inspections).sortedDescending().take(2).reduce(Long::times)
}
fun part1(monkeys: List<Monkey>) = monkeys.keepAway(20) { worry -> (worry / 3.0).toLong() }
fun part2(monkeys: List<Monkey>): Long {
val lcm = monkeys.map(Monkey::test).reduce(Long::times)
return monkeys.keepAway(10000) { worry -> worry % lcm }
}
val input = readInput(::main.javaClass.packageName)
println("Part1=\n" + part1(parse(input)))
println("Part2=\n" + part2(parse(input)))
}
| 0 | Kotlin | 0 | 0 | 9cb653bd6a5abb214a9310f7cac3d0a5a478a71a | 2,556 | AOC2022 | Apache License 2.0 |
src/Day02.kt | marciprete | 574,547,125 | false | {"Kotlin": 13734} | fun main() {
val circularArray = setOf<Char>('A', 'B', 'C', 'X', 'Y', 'Z')
fun score(a: Char, b: Char): Int {
val idA = circularArray.indexOf(a) % 3
val idB = circularArray.indexOf(b) % 3
return when ((idB - idA + 2) % 3) {
2 -> 4 //Draw
1 -> 7 //Win
else -> 1 //Lose
} + idA
}
fun cheat(a: Char, b: Char): Int {
return when (circularArray.indexOf(b) % 3) {
0 -> 1 + (circularArray.indexOf(a) + 2) % 3 //x = lose
1 -> 4 + circularArray.indexOf(a) //y = draw
else -> 7 + (circularArray.indexOf(a) + 1) % 3 //z = win
}
}
fun part1(input: List<String>): Int {
return input.map {
it.split(" ").let {
(score(it.get(1)[0], it.get(0)[0]))
}
}.sum()
}
fun part2(input: List<String>): Int {
return input.map {
it.split(" ").let {
cheat(it.get(0)[0], it.get(1)[0])
}
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6345abc8f2c90d9bd1f5f82072af678e3f80e486 | 1,347 | Kotlin-AoC-2022 | Apache License 2.0 |
src/day13/Day13.kt | treegem | 572,875,670 | false | {"Kotlin": 38876} | package day13
import common.readInput
// i am sorry for the mess, but i fell behind in schedule and will not refactor or optimize this code
// still hoping to catch up
fun main() {
fun part1(input: List<String>) =
input
.asSequence()
.filter { it.isNotBlank() }
.chunked(2)
.map { list -> list.map { it.toListContent() } }
.map { it.first().getOutcome(it.last()) }
.mapIndexedNotNull { index, outcome ->
if (outcome < 0) index + 1 else null
}
.sum()
fun part2(input: List<String>): Int {
val firstSeparator = "[[2]]".toListContent()
val secondSeparator = "[[6]]".toListContent()
val packets = input
.filter { it.isNotBlank() }
.map { it.toListContent() }
.toMutableList()
.also { it.add(firstSeparator) }
.also { it.add(secondSeparator) }
while (!packets.isSorted()) {
packets
.indices
.toList()
.dropLast(1)
.map { index ->
if (packets[index].getOutcome(packets[index + 1]) > 0) {
val originalLeftValue = packets[index]
packets[index] = packets[index + 1]
packets[index + 1] = originalLeftValue
}
}
}
return (packets.indexOf(firstSeparator) + 1) * (packets.indexOf(secondSeparator) + 1)
}
val day = "13"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
}
private fun List<ListContent>.isSorted() =
this.windowed(2)
.map { it.first().getOutcome(it.last()) }
.all { it < 0 }
private fun String.toListContent(): ListContent {
val iterator = this.toCharArray().iterator()
require(iterator.nextChar() == '[')
return parseListContent(iterator)
}
fun parseNumberContent(currentNumber: String, iterator: CharIterator): Pair<NumberContent, Boolean> {
val nextChar = iterator.nextChar()
return if (nextChar.isDigit()) {
parseNumberContent(currentNumber + nextChar, iterator)
} else {
val isEndOfList = nextChar == ']'
NumberContent(currentNumber.toInt()) to isEndOfList
}
}
fun parseListContent(iterator: CharIterator): ListContent {
val resultList = mutableListOf<PacketContent>()
var currentChar = iterator.nextChar()
while (currentChar != ']') {
when {
currentChar.isDigit() -> {
val parseResult = parseNumberContent(currentChar.toString(), iterator)
resultList.add(parseResult.first)
if (parseResult.second) break
}
currentChar == '[' -> resultList.add(parseListContent(iterator))
}
currentChar = iterator.nextChar()
}
return ListContent(resultList.toList())
}
| 0 | Kotlin | 0 | 0 | 97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8 | 3,152 | advent_of_code_2022 | Apache License 2.0 |
src/Day02.kt | DeltaSonic62 | 572,718,847 | false | {"Kotlin": 8676} | fun main() {
fun part1(input: List<String>): Int {
val opponentScoreMap = mapOf("A" to 1, "B" to 2, "C" to 3)
val playerScoreMap = mapOf("X" to 1, "Y" to 2, "Z" to 3)
var score = 0
for (line in input) {
val opponent = line.split(" ")[0]
val player = line.split(" ")[1]
score += playerScoreMap[player] ?: 0
if (playerScoreMap[player] == opponentScoreMap[opponent]) {
score += 3
continue
}
if (player == "X" && opponent == "C" || (!(player == "Z" && opponent == "A") && (playerScoreMap[player]
?: 0) > (opponentScoreMap[opponent] ?: 0))
) score += 6
}
return score
}
fun part2(input: List<String>): Int {
val opponentScoreMap = mapOf("A" to 1, "B" to 2, "C" to 3)
val calcLosePoints = { i: Int -> if (i == 1) 3 else i - 1 }
val calcWinPoints = { i: Int -> if (i == 3) 1 else i + 1 }
var score = 0
for (line in input) {
val opponent = line.split(" ")[0]
when (line.split(" ")[1]) {
"X" -> score += calcLosePoints(opponentScoreMap[opponent]!!)
"Y" -> score += 3 + opponentScoreMap[opponent]!!
"Z" -> score += 6 + calcWinPoints(opponentScoreMap[opponent]!!)
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7cdf94ad807933ab4769ce4995a43ed562edac83 | 1,699 | aoc-2022-kt | Apache License 2.0 |
src/Day02.kt | petitJAM | 572,737,836 | false | {"Kotlin": 4868, "Shell": 749} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { inputLine ->
inputLine.split(" ").let {
val opponent = RPS.fromInput(it[0])
val me = RPS.fromInput(it[1])
scoreGame(me = me, opponent = opponent)
}
}
}
fun part2(input: List<String>): Int {
return input.sumOf { inputLine ->
inputLine.split(" ").let {
val opponent = RPS.fromInput(it[0])
val desiredOutcome = DesiredOutcome.fromInput(it[1])
val iShouldPlay = whatShouldIPlay(opponent, desiredOutcome)
scoreGame(iShouldPlay, opponent)
}
}
}
// 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("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun scoreGame(me: RPS, opponent: RPS): Int {
return when (me) {
RPS.ROCK -> {
1 + when (opponent) {
RPS.ROCK -> 3
RPS.PAPER -> 0
RPS.SCISSORS -> 6
}
}
RPS.PAPER -> {
2 + when (opponent) {
RPS.ROCK -> 6
RPS.PAPER -> 3
RPS.SCISSORS -> 0
}
}
RPS.SCISSORS -> {
3 + when (opponent) {
RPS.ROCK -> 0
RPS.PAPER -> 6
RPS.SCISSORS -> 3
}
}
}
}
private fun whatShouldIPlay(opponent: RPS, desiredOutcome: DesiredOutcome): RPS {
return when (opponent) {
RPS.ROCK -> when (desiredOutcome) {
DesiredOutcome.WIN -> RPS.PAPER
DesiredOutcome.LOSE -> RPS.SCISSORS
DesiredOutcome.DRAW -> RPS.ROCK
}
RPS.PAPER -> when (desiredOutcome) {
DesiredOutcome.WIN -> RPS.SCISSORS
DesiredOutcome.LOSE -> RPS.ROCK
DesiredOutcome.DRAW -> RPS.PAPER
}
RPS.SCISSORS -> when (desiredOutcome) {
DesiredOutcome.WIN -> RPS.ROCK
DesiredOutcome.LOSE -> RPS.PAPER
DesiredOutcome.DRAW -> RPS.SCISSORS
}
}
}
private enum class DesiredOutcome {
WIN,
LOSE,
DRAW;
companion object {
fun fromInput(inputStr: String): DesiredOutcome = when (inputStr) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException("Unknown input $inputStr")
}
}
}
private enum class RPS {
ROCK,
PAPER,
SCISSORS;
companion object {
fun fromInput(inputStr: String): RPS = when (inputStr) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException("Unknown input string $inputStr")
}
}
}
| 0 | Kotlin | 0 | 0 | 1965ded0e0ad09b77e001b1b87ac48f47066f479 | 3,015 | adventofcode2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.