Skip to content

Commit

Permalink
Solve 2023 day 4 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 4, 2023
1 parent 709c617 commit f521f03
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/main/scala/eu/sim642/adventofcode2023/Day4.scala
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package eu.sim642.adventofcode2023

import scala.annotation.tailrec

object Day4 {

case class Card(winning: Set[Int], have: Set[Int]) {
def haveWinning: Int = (winning intersect have).size

def points: Int = {
val haveWinning = (winning intersect have).size
if (haveWinning == 0)
0
else
Expand All @@ -14,6 +17,22 @@ object Day4 {

def sumPoints(cards: Seq[Card]): Int = cards.map(_.points).sum

def countWonCards(cards: Seq[Card]): Int = {

@tailrec
def helper(cardCounts: Seq[(Card, Int)], acc: Int): Int = cardCounts match {
case Seq() => acc
case (card, count) +: newCardCounts =>
val newCardCounts2 = (0 until card.haveWinning).foldLeft(newCardCounts)({ (newCardCounts, i) =>
val (newCard, newCount) = newCardCounts(i)
newCardCounts.updated(i, (newCard, newCount + count))
})
helper(newCardCounts2, acc + count)
}

helper(cards.map(_ -> 1), 0)
}


def parseCard(s: String): Card = s match {
case s"Card $i: $winning | $have" =>
Expand All @@ -29,5 +48,6 @@ object Day4 {

def main(args: Array[String]): Unit = {
println(sumPoints(parseCards(input)))
println(countWonCards(parseCards(input)))
}
}
8 changes: 8 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2023/Day4Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,12 @@ class Day4Test extends AnyFunSuite {
test("Part 1 input answer") {
assert(sumPoints(parseCards(input)) == 23235)
}

test("Part 2 examples") {
assert(countWonCards(parseCards(exampleInput)) == 30)
}

test("Part 2 input answer") {
assert(countWonCards(parseCards(input)) == 5920640)
}
}

0 comments on commit f521f03

Please sign in to comment.