Skip to content

Commit ce8e593

Browse files
authored
Refine day04 solution (#345)
1 parent b4ce704 commit ce8e593

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

2023/src/day04.scala

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,23 +32,24 @@ def countWinning(card: String): Int =
3232
// drop the initial "|"
3333
val givenNumbers = givenNumberStrs.drop(1).map(_.toInt).toSet
3434
winningNumbers.intersect(givenNumbers).size
35+
end countWinning
36+
37+
def winningCounts(input: String): Iterator[Int] =
38+
input.linesIterator.map(countWinning)
39+
end winningCounts
3540

3641
def part1(input: String): String =
37-
input.linesIterator
38-
.map{ line =>
39-
val winning = countWinning(line)
40-
if winning > 0 then Math.pow(2, winning - 1).toInt else 0
41-
}
42+
winningCounts(input)
43+
.map(winning => if winning > 0 then Math.pow(2, winning - 1).toInt else 0)
4244
.sum.toString()
4345
end part1
4446

4547
def part2(input: String): String =
46-
input.linesIterator
48+
winningCounts(input)
4749
// we only track the multiplicities of the next few cards as needed, not all of them;
48-
// and the first element always exists, and corresponds to the current `line`;
50+
// and the first element always exists, and corresponds to the current card;
4951
// and the elements are always positive (because there is at least 1 original copy of each card)
50-
.foldLeft((0, Vector(1))){ case ((numCards, multiplicities), line) =>
51-
val winning = countWinning(line)
52+
.foldLeft((0, Vector(1))){ case ((numCards, multiplicities), winning) =>
5253
val thisMult = multiplicities(0)
5354
val restMult = multiplicities
5455
.drop(1)

0 commit comments

Comments
 (0)