Day 4
This commit is contained in:
parent
caeb832cd5
commit
bfb8326f1d
2 changed files with 278 additions and 0 deletions
58
src/day04.scala
Normal file
58
src/day04.scala
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
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
|
||||
Loading…
Add table
Add a link
Reference in a new issue