-
-
Save waynejo/ec862629ba0e30c337768240e1ef7143 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 | |
case class CubeSet(red: Int = 0, green: Int = 0, blue: Int = 0) | |
object CubeSet: | |
def apply(s: String): CubeSet = | |
s.split(",").foldLeft(CubeSet()) { (acc, x) => | |
val Array(number, color) = x.trim.split(" ") | |
color match { | |
case "red" => acc.copy(red = number.toInt) | |
case "green" => acc.copy(green = number.toInt) | |
case "blue" => acc.copy(blue = number.toInt) | |
case _ => acc | |
} | |
} | |
case class Game(cubes: Vector[CubeSet]) | |
object Game: | |
def apply(s: String): Game = | |
val cubes = s.split(":").last.split(";").map(CubeSet(_)).toVector | |
Game(cubes) | |
def solve2_1(games: Vector[Game], maxCubes: CubeSet): Int = | |
val validGames = games.zipWithIndex.filter { (game, _) => | |
game.cubes.map(_.red).max <= maxCubes.red && game.cubes.map(_.green).max <= maxCubes.green && game.cubes.map(_.blue).max <= maxCubes.blue | |
} | |
validGames.map(_._2 + 1).sum | |
def solve2_2(games: Vector[Game]): Int = | |
games.map { game => | |
game.cubes.map(_.red).max * game.cubes.map(_.green).max * game.cubes.map(_.blue).max | |
}.sum | |
@main def solve2(): Unit = | |
val in = new FileInputStream("example2-2.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()) | |
.takeWhile(line => null != line) | |
.toVector | |
val games: Vector[Game] = inputs.map(Game.apply) | |
println(solve2_1(games, CubeSet(12, 13, 14))) | |
println(solve2_2(games)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment