Solved Day02 and Day03 of 2022.

This commit is contained in:
Chris Hodges 2023-11-22 06:34:49 +01:00
parent 13a3503196
commit 4c4886c1ec
3 changed files with 63 additions and 1 deletions

30
src/aoc2022/Day02.kt Normal file
View File

@ -0,0 +1,30 @@
fun main() {
// A = 0 X = 0 Win: X0 - C2, Z2 - B1, Y1 - A0
// B = 1 Y = 1 Win: (r+2) % 3) == c; Lose: ((r+1) % 3) == c
// C = 2 Z = 2 Points = (r + 1) + ((3-c) - (r+1) % 3) * 3
fun part1(input: List<String>): Int {
return input.sumOf {
val c = it[0] - 'A'
val r = it[2] - 'X'
(r + 1) + ((r - c + 4) % 3) * 3
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val c = it[0] - 'A'
val l = it[2] - 'X'
val r = (l - c * 2 + 8) % 3
(r + 1) + ((r - c + 4) % 3) * 3
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("aoc2022/Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("aoc2022/Day02")
part1(input).println()
part2(input).println()
}

32
src/aoc2022/Day03.kt Normal file
View File

@ -0,0 +1,32 @@
fun main() {
fun toPrio(input: Char) = if (input in 'A'..'Z') input - 'A' + 27 else input - 'a' + 1
fun part1(input: List<String>): Int =
input.sumOf {
val seen = IntArray(2 * 26 + 1)
it.subSequence(0, it.length / 2).forEach { seen[toPrio(it)] = 1 }
it.subSequence(it.length / 2, it.length).forEach { seen[toPrio(it)] = seen[toPrio(it)] or 2 }
seen.withIndex().find { it.value == 3 }!!.index
}
fun part2(input: List<String>): Int =
input.chunked(3)
.sumOf {
val seen = IntArray(2 * 26 + 1)
it[0].forEach { seen[toPrio(it)] = 1 }
it[1].forEach { seen[toPrio(it)] = seen[toPrio(it)] or 2 }
it[2].forEach { seen[toPrio(it)] = seen[toPrio(it)] or 4 }
seen.withIndex().find { it.value == 7 }!!.index
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("aoc2022/Day03_test")
part1(testInput).println()
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("aoc2022/Day03")
part1(input).println()
part2(input).println()
}