Day 6
This commit is contained in:
parent
b1add6f0bf
commit
90c0fa2f75
2 changed files with 62 additions and 0 deletions
1
aoc/resources/day6Input.txt
Normal file
1
aoc/resources/day6Input.txt
Normal file
|
|
@ -0,0 +1 @@
|
|||
3,4,1,1,5,1,3,1,1,3,5,1,1,5,3,2,4,2,2,2,1,1,1,1,5,1,1,1,1,1,3,1,1,5,4,1,1,1,4,1,1,1,1,2,3,2,5,1,5,1,2,1,1,1,4,1,1,1,1,3,1,1,3,1,1,1,1,1,1,2,3,4,2,1,3,1,1,2,1,1,2,1,5,2,1,1,1,1,1,1,4,1,1,1,1,5,1,4,1,1,1,3,3,1,3,1,3,1,4,1,1,1,1,1,4,5,1,1,3,2,2,5,5,4,3,1,2,1,1,1,4,1,3,4,1,1,1,1,2,1,1,3,2,1,1,1,1,1,4,1,1,1,4,4,5,2,1,1,1,1,1,2,4,2,1,1,1,2,1,1,2,1,5,1,5,2,5,5,1,1,3,1,4,1,1,1,1,1,1,1,4,1,1,4,1,1,1,1,1,2,1,2,1,1,1,5,1,1,3,5,1,1,5,5,3,5,3,4,1,1,1,3,1,1,3,1,1,1,1,1,1,5,1,3,1,5,1,1,4,1,3,1,1,1,2,1,1,1,2,1,5,1,1,1,1,4,1,3,2,3,4,1,3,5,3,4,1,4,4,4,1,3,2,4,1,4,1,1,2,1,3,1,5,5,1,5,1,1,1,5,2,1,2,3,1,4,3,3,4,3
|
||||
61
aoc/src/Day6.scala
Normal file
61
aoc/src/Day6.scala
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import scala.io.Source
|
||||
|
||||
object Day6 extends App:
|
||||
|
||||
val input = Source
|
||||
.fromURL(getClass.getResource("day6Input.txt"))
|
||||
.mkString
|
||||
|
||||
final case class Lanternfish(timer: Int = 8):
|
||||
def spendADay(): Seq[Lanternfish] =
|
||||
if (timer == 0) Seq(Lanternfish(6), Lanternfish())
|
||||
else Seq(Lanternfish(timer - 1))
|
||||
|
||||
val initialFishes = input.split(',').toList.map(t => Lanternfish(t.toInt))
|
||||
|
||||
val fishesAfter18Days =
|
||||
(1 to 18).foldLeft(initialFishes)((fishes, _) =>
|
||||
fishes.flatMap(_.spendADay())
|
||||
)
|
||||
println(s"Part 1: ${fishesAfter18Days.size}")
|
||||
|
||||
final case class SchoolOfLanternfish(fishes: Map[Lanternfish, Long]):
|
||||
def spendADay(): SchoolOfLanternfish =
|
||||
val reproducingFishes = fishes(Lanternfish(0))
|
||||
|
||||
SchoolOfLanternfish(
|
||||
(1 to 6)
|
||||
.appended((8))
|
||||
.map(timer => (Lanternfish(timer - 1) -> fishes(Lanternfish(timer))))
|
||||
.prepended(
|
||||
(Lanternfish(6)) -> (fishes(Lanternfish(7)) + reproducingFishes)
|
||||
)
|
||||
.prepended(
|
||||
(Lanternfish(8)) -> reproducingFishes
|
||||
)
|
||||
.toMap
|
||||
)
|
||||
|
||||
def countFishes = fishes.values.sum
|
||||
|
||||
object SchoolOfLanternfish:
|
||||
def apply(fishes: Seq[Lanternfish]): SchoolOfLanternfish =
|
||||
val samples = (0 to 8).map(Lanternfish(_))
|
||||
|
||||
SchoolOfLanternfish(
|
||||
samples.foldLeft(fishes.groupMapReduce(identity)(_ => 1L)(_ + _))(
|
||||
(fishesMap, sample) =>
|
||||
fishesMap.updatedWith(sample) {
|
||||
case Some(count) => Some(count)
|
||||
case None => Some(0)
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
val initialSchool = SchoolOfLanternfish(initialFishes)
|
||||
|
||||
val fishesAfter256Days =
|
||||
(1 to 256)
|
||||
.foldLeft(initialSchool)((school, _) => school.spendADay())
|
||||
.countFishes
|
||||
println(s"Part 2: $fishesAfter256Days")
|
||||
Loading…
Add table
Add a link
Reference in a new issue