-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay21AllergenAssessment.kt
More file actions
63 lines (55 loc) · 2.04 KB
/
Day21AllergenAssessment.kt
File metadata and controls
63 lines (55 loc) · 2.04 KB
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 adventofcode.year2020
import adventofcode.Puzzle
import adventofcode.PuzzleInput
class Day21AllergenAssessment(
customInput: PuzzleInput? = null,
) : Puzzle(customInput) {
private val foods by lazy { input.lines().map(Food::invoke) }
override fun partOne(): Int {
val ingredientsToAllergens = foods.ingredientsAllergensMap()
return foods.flatMap(Food::ingredients).filter { !ingredientsToAllergens.contains(it) }.size
}
override fun partTwo() =
foods
.ingredientsAllergensMap()
.entries
.sortedBy { it.value }
.joinToString(",") { it.key }
companion object {
private data class Food(
val ingredients: List<String>,
val allergens: List<String>,
) {
companion object {
operator fun invoke(input: String): Food {
val ingredients =
input
.split("(")
.first()
.trim()
.split(" ")
val allergens =
when {
input.contains("(") ->
input
.split("(")
.last()
.replace("contains ", "")
.replace(")", "")
.split(", ")
else -> emptyList()
}
return Food(ingredients, allergens)
}
}
}
private fun List<Food>.ingredientsAllergensMap() =
flatMap { food ->
food.allergens.map { allergen ->
food.ingredients.last { ingredient ->
filter { it.allergens.contains(allergen) }.all { it.ingredients.contains(ingredient) }
} to allergen
}
}.toMap()
}
}