Skip to content

Commit

Permalink
2024 Day 05 Part2
Browse files Browse the repository at this point in the history
  • Loading branch information
fmmr committed Dec 5, 2024
1 parent b86fd96 commit 5033bf5
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 12 deletions.
46 changes: 37 additions & 9 deletions src/main/kotlin/no/rodland/advent_2024/Day05.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,49 @@ import no.rodland.advent.Day
// template generated: 05/12/2024
// Fredrik Rødland 2024

class Day05(val input: List<String>) : Day<Int, Long, Pair<List<Pair<Int, Int>>, List<List<Int>>>> {
class Day05(val input: List<String>) : Day<Int, Int, Pair<List<Pair<Int, Int>>, List<List<Int>>>> {

private val parsed = input.parse()
private val rules = parsed.first
private val pages = parsed.second

override fun partOne(): Int {
return pages
.filter { list ->
val pairs = list.pairs()
pairs.all { it in rules }
}
.sumOf { it.middle() }
return pages
.filter { it.valid() }
.sumOf { it.middle() }
}

override fun partTwo(): Long {
return 2
override fun partTwo(): Int {
return pages
.filterNot { it.valid() }
.map { it.reorder() }
.sumOf { it.middle() }
}

private fun List<Int>.valid() = pairs().all { it in rules }

private fun List<Int>.reorder(): List<Int> {
val breaking = pairs()
.filterNot { it in rules }
.groupBy({ it.first }, { it.second })

val fold = breaking.keys.fold(this) { acc, b ->
acc.move(b, breaking[b]!!)
}
return if (fold.valid()){
// println("yeah. $this $fold $breaking")
fold
}else{
// still not right - just run it again
// println("reordering. $this $fold $breaking")
fold.reorder()
}
}

private fun List<Int>.move(element: Int, after: List<Int>): List<Int> {
val indexElement = indexOf(element)
val moveAfter = indexOfLast { it in after }
return subList(0, indexElement) + subList(indexElement + 1, moveAfter + 1) + element + subList(moveAfter + 1, size)
}

private fun List<Int>.middle(): Int = get(size / 2)
Expand Down Expand Up @@ -49,3 +75,5 @@ class Day05(val input: List<String>) : Day<Int, Long, Pair<List<Pair<Int, Int>>,
}




6 changes: 3 additions & 3 deletions src/test/kotlin/no/rodland/advent_2024/Day05Test.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ internal class Day05Test {
private val test05 = "2024/input_05_test.txt".readFile()

private val resultTestOne = 143
private val resultTestTwo = 2L
private val resultTestTwo = 123
private val resultOne = 5762
private val resultTwo = 2L
private val resultTwo = 4130

val test = defaultTestSuiteParseOnInit(
Day05(data05),
Expand All @@ -30,7 +30,7 @@ internal class Day05Test {
{ Day05(data05) },
{ Day05(test05) },
numTestPart1 = 10,
numTestPart2 = 10,
numTestPart2 = 1,
)

@Nested
Expand Down

0 comments on commit 5033bf5

Please sign in to comment.