Adding day 7

This commit is contained in:
Xavier Morel
2018-12-07 15:00:59 +01:00
parent 1c4295ee24
commit 09911c195c
2 changed files with 81 additions and 0 deletions

30
day7/part1.scala Normal file
View File

@@ -0,0 +1,30 @@
import scala.io.StdIn.readLine
// "Step A must be finished before step B can begin."
// 0 1 2 3 4 5 6 7 8 9
val PREREQ_STEP_INDEX: Int = 1
val STEP_INDEX: Int = 7
val stepsWithParents = Iterator.continually(readLine)
.takeWhile(_ != null)
.map { l =>
val ws = l.split(" ")
ws(PREREQ_STEP_INDEX).head -> ws(STEP_INDEX).head }
.foldLeft(Map.empty[Char, Set[Char]]){
case (acc, (parent, child)) => acc +
(child -> (acc.getOrElse(child, Set.empty[Char]) + parent)) +
(parent -> (acc.getOrElse(parent, Set.empty[Char])))}
.toList
def walkGraph(g: List[(Char, Set[Char])], result: String = ""): String = g match {
case Nil => result
case _ =>
val chosenParent = g.filter(_._2.isEmpty).map(_._1).min
walkGraph(
g
.filter(_._1 != chosenParent)
.map { case (k, v) => k -> v.filter(_ != chosenParent) },
result + chosenParent.toString)
}
println(walkGraph(stepsWithParents))