-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay5.kt
63 lines (54 loc) · 1.9 KB
/
Day5.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
package day5
import java.io.File
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.time.seconds
fun main() {
partTwo()
}
fun partOne() {
File("src/main/resources/day5_input.txt").readLines().asSequence()
.map {
it.slice(0..6) to it.slice(7..9)
}
.map {
it.first.findBinaryPartitionValue(128, 'B') to
it.second.findBinaryPartitionValue(8, 'R')
}
.map { it.first*8+it.second }
.maxOrNull()
.apply { println(this) }
}
fun partTwo() {
val knownSeats = File("src/main/resources/day5_input.txt").readLines().asSequence()
.map {
it.slice(0..6) to it.slice(7..9)
}
.map {
Seat.fromPosition(it.first.findBinaryPartitionValue(128, 'B'),
it.second.findBinaryPartitionValue(8, 'R'))
}
.toList()
val knownSeatIds = knownSeats.map{ it.id }
val missingSeats = knownSeats.groupBy { it.row }
.filter { it.value.size < 8 }
.map { rowMapEntry -> rowMapEntry.key to (0..7)-rowMapEntry.value.map { it.col }.toList() }
.flatMap { mapEntry ->
mapEntry.second.map {
Seat.fromPosition(mapEntry.first, it)
}
}.filter {
knownSeatIds.contains(it.id+1) && knownSeatIds.contains(it.id-1)
}
println(missingSeats)
}
data class Seat(val id: Int, val col: Int, val row: Int) {
companion object {
fun fromPosition(col: Int, row: Int): Seat = Seat(col*8+row, row, col)
}
}
fun String.findBinaryPartitionValue(maxValue: Int, highChar: Char): Int =
this.foldIndexed(0) { idx, seat, char ->
seat + if(char == highChar) maxValue/2.pow(idx+1) else 0
}
fun Int.pow(exp: Int): Int = this.toFloat().pow(exp).roundToInt()