-
-
Save waynejo/91869f223fdbb7a37458daf4be19c2f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileInputStream | |
import scala.io.StdIn | |
@main def solve7() = | |
def solve(colorLinks: Map[String, Vector[String]], firstBag: String): Int = { | |
def findBags(bag: String): Set[String] = { | |
val nexts = colorLinks.getOrElse(bag, Vector()) | |
nexts.flatMap(findBags).toSet ++ nexts.toSet | |
} | |
findBags(firstBag).size | |
} | |
val in = new FileInputStream("example7-1.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()).takeWhile(_ != null).toVector | |
val colorLinks = inputs.foldLeft(Map[String, Vector[String]]()) { (acc, line) => | |
val Array(parent, children) = line.trim.init.replace("bags", "bag").split("contain") | |
children.split(",").foldLeft(acc) { (subAcc, bag) => | |
val child: String = bag.filter(!_.isDigit).trim | |
subAcc.updated(child, subAcc.getOrElse(child, Vector()) :+ parent.trim) | |
} | |
} | |
println(solve(colorLinks, "shiny gold bag")) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileInputStream | |
import scala.io.StdIn | |
@main def solve7() = | |
def solve(colorLinks: Map[String, Vector[(Int, String)]], firstBag: String): Int = { | |
def childBagCount(bag: String): Int = { | |
val nexts = colorLinks.getOrElse(bag, Vector()) | |
nexts.map { x => x._1 * (1 + childBagCount(x._2)) }.sum | |
} | |
childBagCount(firstBag) | |
} | |
val in = new FileInputStream("example7-1.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()).takeWhile(_ != null).toVector | |
val colorLinks = inputs.foldLeft(Map[String, Vector[(Int, String)]]()) { (acc, line) => | |
val Array(parent, children) = line.trim.init.replace("bags", "bag").split("contain") | |
children.split(",").foldLeft(acc) { (subAcc, bag) => | |
val child: String = bag.filter(!_.isDigit) | |
val count = ("0" + bag.filter(_.isDigit)).toInt | |
subAcc.updated(parent.trim, subAcc.getOrElse(parent.trim, Vector()) :+ (count, child.trim)) | |
} | |
} | |
println(solve(colorLinks, "shiny gold bag")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment