day 2 puzzle 1

This commit is contained in:
Louis Heredero 2023-12-02 11:39:19 +01:00
parent 12240f6d8c
commit 3395f8848f
3 changed files with 77 additions and 0 deletions

57
src/day2/Puzzle1.scala Normal file
View File

@ -0,0 +1,57 @@
package day2
import scala.collection.immutable.HashMap
import scala.collection.mutable.ArrayBuffer
import scala.io.{BufferedSource, Source}
object Puzzle1 {
var games: Array[String] = new Array(0)
def loadInput(path: String): Unit = {
val source: BufferedSource = Source.fromFile(path)
games = source.getLines().toArray
source.close()
}
def getPossible(content: Map[String, Int]): ArrayBuffer[Int] = {
val result: ArrayBuffer[Int] = new ArrayBuffer()
for (game: String <- games) {
val parts: Array[String] = game.split(": ")
val gameId: Int = parts(0).split(" ")(1).toInt
val sets: Array[String] = parts(1).split("; ")
if (isGamePossible(sets, content)) {
result.addOne(gameId)
}
}
return result
}
def isGamePossible(sets: Array[String], content: Map[String, Int]): Boolean = {
for (set: String <- sets) {
val groups: Array[String] = set.split(", ")
for (group: String <- groups) {
val parts: Array[String] = group.split(" ")
val count: Int = parts(0).toInt
val color: String = parts(1)
if (content(color) < count) return false
}
}
return true
}
def solve(path: String, content: Map[String, Int]): Int = {
loadInput(path)
val possibleGames: Array[Int] = getPossible(content).toArray
return possibleGames.sum
}
def main(args: Array[String]): Unit = {
val solution: Int = solve("res/day2/input1.txt", HashMap(
"red" -> 12,
"green" -> 13,
"blue" -> 14
))
println(solution)
}
}

View File

@ -0,0 +1,15 @@
package day2
import org.scalatest.funsuite.AnyFunSuite
import scala.collection.immutable.HashMap
class Puzzle1Test extends AnyFunSuite {
test("Puzzle1.solve") {
assert(Puzzle1.solve("tests_res/day2/input1.txt", HashMap(
"red" -> 12,
"green" -> 13,
"blue" -> 14
)) == 8)
}
}

View File

@ -0,0 +1,5 @@
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green