1
0
This commit is contained in:
Hubert Van De Walle 2020-12-22 06:12:28 +01:00
parent 9490164d09
commit e54fa1b187
3 changed files with 135 additions and 1 deletions

View File

@ -25,7 +25,7 @@ class Day21(@Lines val input: Input<List<String>>) {
val occurrences = Bags.mutable.empty<String>()
foods.forEach { (ingredients) -> occurrences.addAll(ingredients) }
return allIngredients.filter { !dangerousIngredients.containsValue(it) }
.map { occurrences.count { it == it } }
.map { ingredient -> occurrences.count { it == ingredient } }
.sum()
}

View File

@ -0,0 +1,81 @@
package be.vandewalleh.aoc.days
import be.vandewalleh.aoc.utils.input.Day
import be.vandewalleh.aoc.utils.input.Groups
import be.vandewalleh.aoc.utils.input.Input
import be.vandewalleh.aoc.utils.input.createDay
data class PlayedGame(val a: List<Int>, val b: List<Int>)
@Day(22)
class Day22(@Groups val input: Input<List<List<String>>>) {
private val one = input.value[0].drop(1).map { it.toInt() }
private val two = input.value[1].drop(1).map { it.toInt() }
fun part1(): Long {
val oneDeque = ArrayDeque<Int>().apply { one.forEach { addFirst(it) } }
val twoDeque = ArrayDeque<Int>().apply { two.forEach { addFirst(it) } }
while (oneDeque.isNotEmpty() && twoDeque.isNotEmpty()) {
val a = oneDeque.removeLast()
val b = twoDeque.removeLast()
if (a > b) {
oneDeque.addFirst(a)
oneDeque.addFirst(b)
} else {
twoDeque.addFirst(b)
twoDeque.addFirst(a)
}
}
val deque = if (oneDeque.isEmpty()) twoDeque else oneDeque
return deque.mapIndexed { index, value -> (index + 1).toLong() * value.toLong() }.sum()
}
fun part2(): Long {
val oneDeque = ArrayDeque<Int>().apply { one.forEach { addFirst(it) } }
val twoDeque = ArrayDeque<Int>().apply { two.forEach { addFirst(it) } }
val winner = playGame(oneDeque, twoDeque)
val deque = if (winner == 1) oneDeque else twoDeque
return deque.mapIndexed { index, value -> (index + 1).toLong() * value.toLong() }.sum()
}
private fun playGame(one: ArrayDeque<Int>, two: ArrayDeque<Int>): Int {
val playedGames = mutableSetOf<PlayedGame>()
while (one.isNotEmpty() && two.isNotEmpty()) {
if (!playedGames.add(PlayedGame(one.toList(), two.toList()))) return 1
val a = one.removeLast()
val b = two.removeLast()
val winner = when {
one.size >= a && two.size >= b -> playGame(
ArrayDeque(one.drop(one.size - a)),
ArrayDeque(two.drop(two.size - b))
)
a > b -> 1
else -> 2
}
if (winner == 1) {
one.addFirst(a)
one.addFirst(b)
} else {
two.addFirst(b)
two.addFirst(a)
}
}
return if (one.isEmpty()) 2 else 1
}
}
fun main() = with(createDay<Day22>()) {
println(part1())
println(part2())
}

View File

@ -0,0 +1,53 @@
Player 1:
21
48
44
31
29
5
23
11
12
27
49
22
18
7
15
20
2
45
14
17
40
35
6
24
41
Player 2:
47
1
10
16
28
37
8
26
46
25
3
9
34
50
32
36
43
4
42
33
19
13
38
39
30