Skip to content

Commit 6128c99

Browse files
committed
Solution 2018-14 (Chocolate Charts)
1 parent 758810e commit 6128c99

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package de.ronny_h.aoc.year2018.day14
2+
3+
import de.ronny_h.aoc.AdventOfCode
4+
5+
fun main() = ChocolateCharts().run("5992684592", "20181148")
6+
7+
class ChocolateCharts : AdventOfCode<String>(2018, 14) {
8+
override fun part1(input: List<String>): String {
9+
val numberOfRecipes = input.single().toInt()
10+
return ScoreBoard()
11+
.createNewRecipesUntil { it.size == numberOfRecipes + 10 }
12+
.substring(numberOfRecipes, numberOfRecipes + 10)
13+
}
14+
15+
override fun part2(input: List<String>): String {
16+
val inputString = input.single()
17+
val puzzleInput = inputString.toList().map(Char::digitToInt)
18+
return ScoreBoard()
19+
.createNewRecipesUntil { it.endsWithSubList(puzzleInput) }
20+
.substringBefore(inputString).length.toString()
21+
}
22+
}
23+
24+
private fun List<Int>.endsWithSubList(sublist: List<Int>): Boolean {
25+
if (size < sublist.size) return false
26+
return subList(size - sublist.size, size) == sublist
27+
}
28+
29+
private class ScoreBoard {
30+
private val scores = mutableListOf(3, 7)
31+
32+
fun createNewRecipesUntil(stopCondition: (List<Int>) -> Boolean): String {
33+
var indexOne = 0
34+
var indexTwo = 1
35+
while (true) {
36+
val scoreOne = scores[indexOne]
37+
val scoreTwo = scores[indexTwo]
38+
"${scoreOne + scoreTwo}".forEach {
39+
scores.add(it.digitToInt())
40+
if (stopCondition(scores)) {
41+
return scores.joinToString("")
42+
}
43+
}
44+
indexOne = (indexOne + 1 + scoreOne) % scores.size
45+
indexTwo = (indexTwo + 1 + scoreTwo) % scores.size
46+
}
47+
}
48+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package de.ronny_h.aoc.year2018.day14
2+
3+
import io.kotest.core.spec.style.StringSpec
4+
import io.kotest.data.forAll
5+
import io.kotest.data.row
6+
import io.kotest.matchers.shouldBe
7+
8+
class ChocolateChartsTest : StringSpec({
9+
10+
"part 1: the scores of the next 10 recipes after" {
11+
forAll(
12+
row(5, "0124515891"),
13+
row(9, "5158916779"),
14+
row(18, "9251071085"),
15+
row(2018, "5941429882"),
16+
) { after, scores ->
17+
ChocolateCharts().part1(listOf("$after")) shouldBe scores
18+
}
19+
}
20+
21+
"part 2: the number of recipes appear on the scoreboard to the left of the score sequence in the puzzle input" {
22+
forAll(
23+
row("01245", "5"),
24+
row("51589", "9"),
25+
row("92510", "18"),
26+
row("59414", "2018"),
27+
) { puzzleInput, numberOfRecipesBefore ->
28+
ChocolateCharts().part2(listOf(puzzleInput)) shouldBe numberOfRecipesBefore
29+
}
30+
}
31+
})

0 commit comments

Comments
 (0)