Last active
January 14, 2022 22:56
-
-
Save eugene70/2022c9361817ce4c0262caaac5c8a524 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package aoc2021 | |
object Day06: | |
type InputType = Seq[Int] | |
@main def runDay06(): Unit = | |
val testData = time("testReady", () => ready(testInput)) | |
time("testPart1", () => part1(testData)) // should be 5934 | |
time("testPart2", () => part2(testData)) // should be 26984457539 | |
val data = time("ready", () => ready(input)) | |
time("part1", () => part1(data)) | |
time("part2", () => part2(data)) | |
def ready(input: String): InputType = | |
input | |
.linesIterator | |
.flatMap(_.split(",")) | |
.map(_.toInt) | |
.toIndexedSeq | |
def part1(data: InputType): Long = | |
// naive solution | |
Range(0, 80).foldLeft(data)((fishes, i) => { | |
val next = fishes.map(timer => if (timer == 0) 6 else timer - 1) | |
next ++ Seq.fill(fishes.count(n => n == 0))(8) | |
}).length | |
def part2(data: InputType): Long = | |
val initial = data.foldLeft(Vector.fill(9)(0L))((l, n) => l.updated(n, l(n) + 1)) | |
Range(0, 256).foldLeft(initial)((counters, n) => { | |
val rotated = counters.tail :+ counters.head | |
rotated.updated(6, rotated(6) + counters(0)) | |
}).sum | |
private val testInput = | |
"""3,4,3,1,2""".stripMargin | |
private val input = | |
"""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""".stripMargin |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment