day 4 puzzle 2

This commit is contained in:
Louis Heredero 2023-12-04 07:44:35 +01:00
parent 6a9dfc8ef1
commit 9f27d02b93
3 changed files with 65 additions and 8 deletions

View File

@ -5,11 +5,11 @@ This repo contains my attempt at this year's Advent of Code (2023)
I will try and do some problems (probably not all of them) in Scala
## Progress:
#### Stars: 7 / 50
| Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|:-----------:|:---:|:---:|:---:|:-----------------:|:-----------------:|:-----------------:|
| | | | | 1<br>:star::star: | 2<br>:star::star: | 3<br>:star::star: |
| 4<br>:star: | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | | | | | | |
#### Stars: 8 / 50
| Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|:-----------------:|:---:|:---:|:---:|:-----------------:|:-----------------:|:-----------------:|
| | | | | 1<br>:star::star: | 2<br>:star::star: | 3<br>:star::star: |
| 4<br>:star::star: | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | | | | | | |

48
src/day4/Puzzle2.scala Normal file
View File

@ -0,0 +1,48 @@
package day4
import scala.collection.mutable
import scala.io.{BufferedSource, Source}
object Puzzle2 {
case class Card(id: Int, validNumbers: Array[Int], myNumbers: Array[Int], var score: Int = 0, var count: Int = 1)
var cards: Array[Card] = Array.empty
def loadInput(path: String): Unit = {
val source: BufferedSource = Source.fromFile(path)
val lines: Array[String] = source.getLines().toArray
cards = new Array(lines.length)
for ((line: String, i: Int) <- lines.zipWithIndex) {
val parts: Array[String] = line.split(": +")(1).split(" +\\| +")
val validNumbers: Array[Int] = parts(0).split(" +").map(n => n.toInt)
val myNumbers: Array[Int] = parts(1).split(" +").map(n => n.toInt)
cards(i) = Card(i, validNumbers, myNumbers)
}
source.close()
}
def computeScores(): Unit = {
for (card: Card <- cards) {
card.score = card.validNumbers.intersect(card.myNumbers).length
}
}
def solve(path: String): Int = {
loadInput(path)
computeScores()
var count: Int = 0
for (card: Card <- cards) {
count += card.count
for (i: Int <- 0 until card.score) {
cards(card.id + i + 1).count += card.count
}
}
return count
}
def main(args: Array[String]): Unit = {
val solution: Int = solve("res/day4/input1.txt")
println(solution)
}
}

View File

@ -0,0 +1,9 @@
package day4
import org.scalatest.funsuite.AnyFunSuite
class Puzzle2Test extends AnyFunSuite {
test("Puzzle2.solve") {
assert(Puzzle2.solve("tests_res/day4/input1.txt") == 30)
}
}