-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay03.kt
64 lines (51 loc) · 1.97 KB
/
Day03.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package aoc.years.year2021
import aoc.Day
@Year2021
class Day03 : Day() {
override fun solvePart1(input: List<String>): Any {
val gamma = input.first().indices
.fold("") { gamma, index -> gamma.plus(input.mostCommonBitAt(index)) }
.toInt(2)
val epsilon = input.first().indices
.fold("") { epsilon, index -> epsilon.plus(input.leastCommonBitAt(index)) }
.toInt(2)
return gamma * epsilon
}
override fun solvePart2(input: List<String>): Any {
val oxygenGeneratorRating = input.oxygenGeneratorRating()
val co2ScrubberRating = input.co2ScrubberRating()
return oxygenGeneratorRating * co2ScrubberRating
}
}
private fun List<String>.mostCommonBitAt(index: Int): Char {
val (nrOfZeroBits, nrOfOneBits) = countBits(index)
return if (nrOfOneBits >= nrOfZeroBits) '1' else '0'
}
private fun List<String>.leastCommonBitAt(index: Int): Char {
val (nrOfZeroBits, nrOfOneBits) = countBits(index)
return if (nrOfOneBits >= nrOfZeroBits) '0' else '1'
}
private fun List<String>.countBits(index: Int): Pair<Int, Int> {
val nrOfZeroBits = this.count { it.elementAt(index) == '0' }
val nrOfOneBits = this.count { it.elementAt(index) == '1' }
return Pair(nrOfZeroBits, nrOfOneBits)
}
private fun List<String>.oxygenGeneratorRating(): Int {
return this.getRating(List<String>::mostCommonBitAt)
}
private fun List<String>.co2ScrubberRating(): Int {
return this.getRating(List<String>::leastCommonBitAt)
}
private fun List<String>.getRating(findBitFunction: List<String>.(Int) -> Char): Int {
var currentList = this
currentList.first().indices
.forEach {index ->
if (currentList.size > 1) {
val bitToMatch = currentList.findBitFunction(index)
currentList = currentList.filter {
it.elementAt(index) == bitToMatch
}
}
}
return currentList.first().toInt(2)
}