Skip to content

Commit

Permalink
Day 4 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
benoitpas committed Dec 4, 2023
1 parent 0e30206 commit 7bc1b6e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
20 changes: 16 additions & 4 deletions src/main/scala/day4.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ import zio._
import zio.Console._

object Day4 extends ZIOAppDefault {
def cardValue(card: String) =
val winningNumbers :: draw :: _ = card.split(':')(1).split('|').toList
def parseCard(card: String): (Int, Int) =
val idString :: numbers :: _ = card.split(':').toList
val id = idString.split(' ').last.toInt
val winningNumbers :: draw :: _ = numbers.split('|').toList

def toSet(numbers: String) = numbers
.split(' ')
.flatMap {
Expand All @@ -12,14 +15,23 @@ object Day4 extends ZIOAppDefault {
}
.toSet
val nbWinningNumbers = (toSet(winningNumbers) intersect toSet(draw)).size
math.pow(2, nbWinningNumbers - 1).toInt
(id, nbWinningNumbers)

def part1(cards: List[String]) =
cards.map(cardValue).sum
cards.map { card => math.pow(2, parseCard(card)._2 - 1).toInt }.sum

def part2(cards: List[String]) =
val cm = cards.map(parseCard).toMap

def countCards(index: Int): Int =
1 + ((index + 1) to (index + cm(index))).map(countCards).sum

(1 to cm.size).map(countCards).sum

def run =
for {
v <- Day1.readFile("day4_input.txt")
_ <- printLine(s"part1=${part1(v)}")
_ <- printLine(s"part2=${part2(v)}")
} yield ()
}
12 changes: 10 additions & 2 deletions src/test/scala/day4_test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,19 @@ class Day4Test {
"Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11"
)

val winningNumbers = Set(41, 48, 83, 86, 17)
val draw = Set(83, 86, 6, 31, 17, 9, 48, 53)

@Test
def testCardValue() =
assertEquals(8, Day4.cardValue(cards(0)))
def testParseCard() =
assertEquals((1, 4), Day4.parseCard(cards(0)))

@Test
def testPart1() =
assertEquals(13, Day4.part1(cards))

@Test
def testPart2() =
assertEquals(30, Day4.part2(cards))

}

0 comments on commit 7bc1b6e

Please sign in to comment.