-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day04.kt
54 lines (43 loc) · 1.53 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
package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
import kotlin.math.pow
class Day04 : Day(4, 2023, "Scratchcards") {
private fun parseMatches(input: List<String>): Map<Int, Int> {
return input.associate { line ->
val (card, game) = line.split(":")
val cardId = card.split("\\s+".toRegex())[1].toInt()
val (winningNumbers, yourNumbers) = game.split("|")
val winningNumberList = winningNumbers.trim().split("\\s+".toRegex())
val yourNumberList = yourNumbers.trim().split("\\s+".toRegex())
val matches = yourNumberList.count { it in winningNumberList }
cardId to matches
}
}
override fun part1(): Int {
return parseMatches(inputAsList)
.map { (_, matches) ->
if (matches == 0) {
0
} else {
2.0.pow(matches.toDouble() - 1).toInt()
}
}
.sum()
}
override fun part2(): Int {
val cards = parseMatches(inputAsList)
val scratchcards = MutableList(cards.size) {
0
}
cards.forEach { (id, score) ->
val currentIndex = id - 1
scratchcards[currentIndex]++
for (i in 1..score) {
if (currentIndex + i in scratchcards.indices) {
scratchcards[currentIndex + i] += scratchcards[currentIndex]
}
}
}
return scratchcards.sum()
}
}