-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day04.kt
executable file
·68 lines (60 loc) · 2.18 KB
/
Day04.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
65
66
67
68
import kotlin.math.abs
import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val winningNumbers = line
.substringAfter(":")
.substringBefore("|")
.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.toSet()
val winningMatches = line
.substringAfter(":")
.substringAfter("|")
.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.toSet()
val matchCount = winningNumbers.intersect(winningMatches).size
if (matchCount > 0) 1.shl(matchCount - 1) else 0
}
}
fun part2(input: List<String>): Int {
val scratchCards = mutableMapOf<Int, Int>()
input.mapIndexed { idx, line ->
if (!scratchCards.containsKey(idx)) {
scratchCards[idx] = 1
} else {
scratchCards[idx] = scratchCards[idx]!! + 1
}
val winningNumbers = line
.substringAfter(":")
.substringBefore("|")
.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.toSet()
val winningMatches = line
.substringAfter(":")
.substringAfter("|")
.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.toSet()
val matchCount = winningNumbers.intersect(winningMatches).size
repeat(matchCount) {
scratchCards[idx + it + 1] = (scratchCards[idx + it + 1] ?: 0) + scratchCards[idx]!!
}
}
return scratchCards.map { it.value }.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 13)
check(part2(testInput) == 30)
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}