11package eu .sim642 .adventofcode2024
22
3+ import scala .annotation .tailrec
4+
35object Day5 {
46
57 type Rule = (Int , Int )
@@ -23,6 +25,33 @@ object Day5 {
2325 .sum
2426 }
2527
28+ def sort (rules : Seq [Rule ], update : Update ): Update = {
29+ val updateRules = rules.filter(rule => update.contains(rule._1) && update.contains(rule._2))
30+ val updateRulesMap = updateRules.toSet.groupMap(_._1)(_._2).withDefaultValue(Set .empty)
31+
32+ // TODO: optimize?
33+ @ tailrec
34+ def topologicalSort (pages : Set [Int ], updateRulesMap : Map [Int , Set [Int ]], sortedUpdate : List [Int ]): List [Int ] = {
35+ pages.find(updateRulesMap(_).isEmpty) match {
36+ case None => sortedUpdate
37+ case Some (before) =>
38+ val newUpdateRulesMap = (updateRulesMap - before).view.mapValues(_ - before).toMap
39+ topologicalSort(pages - before, newUpdateRulesMap, before :: sortedUpdate)
40+ }
41+ }
42+
43+ topologicalSort(update.toSet, updateRulesMap, Nil )
44+ }
45+
46+ def sumIncorrectMiddles (input : Input ): Int = {
47+ val Input (rules, updates) = input
48+ updates
49+ .filter(! isCorrect(rules, _))
50+ .map(sort(rules, _))
51+ .map(update => update(update.size / 2 ))
52+ .sum
53+ }
54+
2655 def parseRule (s : String ): Rule = s match {
2756 case s " $x| $y" => (x.toInt, y.toInt)
2857 }
@@ -40,5 +69,6 @@ object Day5 {
4069
4170 def main (args : Array [String ]): Unit = {
4271 println(sumCorrectMiddles(parseInput(input)))
72+ println(sumIncorrectMiddles(parseInput(input)))
4373 }
4474}
0 commit comments