Skip to content

Commit 5108719

Browse files
committed
Define addition and scalar multiplication on Ingredient
Making the fold operation much better to read.
1 parent cb51a7f commit 5108719

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

src/main/kotlin/de/ronny_h/aoc/year2015/day15/ScienceForHungryPeople.kt

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,7 @@ class ScienceForHungryPeople : AdventOfCode<Int>(2015, 15) {
3636
teaspoons: List<Int>
3737
): Int {
3838
val sums = ingredients.foldIndexed(Ingredient(0, 0, 0, 0, 0)) { i, acc, ingredient ->
39-
Ingredient(
40-
capacity = acc.capacity + teaspoons[i] * ingredient.capacity,
41-
durability = acc.durability + teaspoons[i] * ingredient.durability,
42-
flavor = acc.flavor + teaspoons[i] * ingredient.flavor,
43-
texture = acc.texture + teaspoons[i] * ingredient.texture,
44-
calories = acc.calories + teaspoons[i] + ingredient.calories,
45-
)
39+
acc + ingredient * teaspoons[i]
4640
}.let {
4741
Ingredient(
4842
capacity = max(it.capacity, 0),
@@ -69,4 +63,20 @@ fun List<String>.parseIngredients() = this.map {
6963

7064
private fun String.secondAsInt(): Int = split(" ")[1].toInt()
7165

72-
data class Ingredient(val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int)
66+
data class Ingredient(val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int) {
67+
operator fun plus(other: Ingredient) = Ingredient(
68+
capacity + other.capacity,
69+
durability + other.durability,
70+
flavor + other.flavor,
71+
texture + other.texture,
72+
calories + other.calories,
73+
)
74+
75+
operator fun times(factor: Int) = Ingredient(
76+
capacity * factor,
77+
durability * factor,
78+
flavor * factor,
79+
texture * factor,
80+
calories * factor,
81+
)
82+
}

0 commit comments

Comments
 (0)