forked from matelaszlo/advent-of-code-scala
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay13.scala
27 lines (19 loc) · 1.1 KB
/
Day13.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.lmat.adventofcode.year2017
import com.lmat.adventofcode.SimpleCommonPuzzle
import com.lmat.util.Files.readResource
object Day13 extends SimpleCommonPuzzle[Map[Int, Int], Int, Int] {
override def parse(resource: String): Map[Int, Int] = parseLayers(readResource(resource))
def parseLayers(rows: Seq[String]): Map[Int, Int] =
rows.map(_.split(": ")).groupBy(_.head.toInt).view.mapValues(_.head(1).toInt).toMap
override def part1(layers: Map[Int, Int]): Int = calculateSeverity(layers, 0)
def calculateSeverity(layers: Map[Int, Int], delay: Int): Int =
layers.filter { case (layer, layerSize) => fallsOnZero(layer, layerSize, delay) }
.map { case (layer, layerSize) => layer * layerSize }
.sum
def fallsOnZero(layer: Int, layerSize: Int, delay: Int): Boolean =
(delay + layer) % ((layerSize - 1) * 2) == 0
override def part2(layers: Map[Int, Int]): Int =
LazyList.from(0).find(delay => canEscape(layers, delay)).get
def canEscape(layers: Map[Int, Int], delay: Int): Boolean =
layers.forall { case (layer, layerSize) => !fallsOnZero(layer, layerSize, delay) }
}