59 lines
1.3 KiB
Scala
59 lines
1.3 KiB
Scala
|
|
package aoc
|
||
|
|
package day04
|
||
|
|
|
||
|
|
import scala.collection.mutable
|
||
|
|
|
||
|
|
val dayNumber = "04"
|
||
|
|
|
||
|
|
@main def part1: Unit =
|
||
|
|
println(part1(loadInput(dayNumber)))
|
||
|
|
|
||
|
|
@main def part2: Unit =
|
||
|
|
println(part2(loadInput(dayNumber)))
|
||
|
|
|
||
|
|
def part1(input: String): String =
|
||
|
|
input
|
||
|
|
.split('\n')
|
||
|
|
.map { case s"$_: $winning | $numbers" =>
|
||
|
|
(
|
||
|
|
winning.split(" ").flatMap(_.toIntOption),
|
||
|
|
numbers.split(" ").flatMap(_.toIntOption)
|
||
|
|
)
|
||
|
|
}
|
||
|
|
.map((w, n) => w.intersect(n).length)
|
||
|
|
.filter(_ > 0)
|
||
|
|
.map(l => Math.pow(2, l - 1).toInt)
|
||
|
|
.sum
|
||
|
|
.toString
|
||
|
|
|
||
|
|
def part2(input: String): String =
|
||
|
|
|
||
|
|
final case class Card(
|
||
|
|
matchingCards: List[Int],
|
||
|
|
instances: Int = 1
|
||
|
|
):
|
||
|
|
def addInstances(n: Int) = copy(instances = instances + n)
|
||
|
|
|
||
|
|
val cards =
|
||
|
|
input
|
||
|
|
.split('\n')
|
||
|
|
.map { case s"$_: $winning | $numbers" =>
|
||
|
|
winning
|
||
|
|
.split(" ")
|
||
|
|
.flatMap(_.toIntOption)
|
||
|
|
.intersect(numbers.split(" ").flatMap(_.toIntOption))
|
||
|
|
.length
|
||
|
|
}
|
||
|
|
.zipWithIndex
|
||
|
|
.map((count, index) => Card((1 to count).map(_ + index).toList))
|
||
|
|
.to(mutable.ArraySeq)
|
||
|
|
|
||
|
|
for card <- cards do
|
||
|
|
for index <- card.matchingCards do
|
||
|
|
cards.update(index, cards(index).addInstances(card.instances))
|
||
|
|
|
||
|
|
cards
|
||
|
|
.map(_.instances)
|
||
|
|
.sum
|
||
|
|
.toString
|