day(03): add solution
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
e8673460a2
commit
5b448e201e
3 changed files with 1071 additions and 0 deletions
59
src/Day03.kt
Normal file
59
src/Day03.kt
Normal file
|
@ -0,0 +1,59 @@
|
|||
fun main() {
|
||||
fun toBits(input: List<String>): List<List<Int>> {
|
||||
return input.map { row ->
|
||||
row.map { if (it == '1') 1 else 0 }
|
||||
}
|
||||
}
|
||||
|
||||
fun part1(input: List<List<Int>>): Int {
|
||||
var gamma = 0
|
||||
var epsilon = 0
|
||||
|
||||
for (i in input[0].indices) {
|
||||
gamma = gamma.shl(1)
|
||||
epsilon = epsilon.shl(1)
|
||||
|
||||
val ones = input.indices.map { input[it][i] }.sum()
|
||||
|
||||
if (2 * ones > input.size) {
|
||||
gamma++
|
||||
} else {
|
||||
epsilon++
|
||||
}
|
||||
}
|
||||
|
||||
return epsilon * gamma
|
||||
}
|
||||
|
||||
fun part2(input: List<List<Int>>): Int {
|
||||
fun part2Helper(predicate: (Int, Int) -> Boolean): Int {
|
||||
var wanted = input.indices.toList()
|
||||
var i = 0
|
||||
|
||||
while (wanted.size > 1) {
|
||||
val ones = wanted.sumOf { input[it][i] }
|
||||
val wantedBit = if (predicate(ones, wanted.size)) 1 else 0
|
||||
|
||||
wanted = wanted.filter { input[it][i] == wantedBit }.toList()
|
||||
i++
|
||||
}
|
||||
|
||||
return input[wanted[0]].fold(0) { n, d -> 2 * n + d }
|
||||
}
|
||||
|
||||
val oxygenGeneratorRating = part2Helper { ones, length -> 2 * ones >= length }
|
||||
val co2ScrubberRating = part2Helper { ones, length -> 2 * ones < length }
|
||||
|
||||
return oxygenGeneratorRating * co2ScrubberRating
|
||||
}
|
||||
|
||||
|
||||
val testInput = toBits(readInput("Day03_test"))
|
||||
val input = toBits(readInput("Day03"))
|
||||
|
||||
check(part1(testInput) == 198)
|
||||
println(part1(input))
|
||||
|
||||
check(part2(testInput) == 230)
|
||||
println(part2(input))
|
||||
}
|
1000
src/Day03.txt
Normal file
1000
src/Day03.txt
Normal file
File diff suppressed because it is too large
Load diff
12
src/Day03_test.txt
Normal file
12
src/Day03_test.txt
Normal file
|
@ -0,0 +1,12 @@
|
|||
00100
|
||||
11110
|
||||
10110
|
||||
10111
|
||||
10101
|
||||
01111
|
||||
00111
|
||||
11100
|
||||
10000
|
||||
11001
|
||||
00010
|
||||
01010
|
Loading…
Reference in a new issue