This commit is contained in:
Paul-Henri Froidmont 2021-12-09 04:10:12 +01:00
parent 0f233d908d
commit b1add6f0bf
Signed by: phfroidmont
GPG key ID: BE948AFD7E7873BE
2 changed files with 564 additions and 0 deletions

64
aoc/src/Day5.scala Normal file
View file

@ -0,0 +1,64 @@
import scala.io.Source
object Day5 extends App:
val input = Source
.fromURL(getClass.getResource("day5Input.txt"))
.mkString
final case class Coordinates(x: Int, y: Int)
object Coordinates:
def parse(input: String): Coordinates =
input.split(',') match
case Array(x, y) => Coordinates(x.toInt, y.toInt)
final case class Line(from: Coordinates, to: Coordinates):
def spannedCoordinates: Seq[Coordinates] =
if (from.x == to.x)
Range
.inclusive(from.y, to.y, if (from.y < to.y) 1 else -1)
.map(Coordinates(from.x, _))
else if (from.y == to.y)
Range
.inclusive(from.x, to.x, if (from.x < to.x) 1 else -1)
.map(Coordinates(_, from.y))
else
Seq()
def spannedCoordinatesIncludingDiagonal: Seq[Coordinates] =
val xs =
if (from.x == to.x) LazyList.continually(from.x)
else Range.inclusive(from.x, to.x, if (from.x < to.x) 1 else -1)
val ys =
if (from.y == to.y) LazyList.continually(from.y)
else
Range.inclusive(from.y, to.y, if (from.y < to.y) 1 else -1)
xs.zip(ys).map(Coordinates.apply).toList
object Line:
def parse(input: String): Line =
input.split(" -> ") match
case Array(from, to) =>
Line(Coordinates.parse(from), Coordinates.parse(to))
val lines = input
.split('\n')
.map(Line.parse)
.toList
def countDuplicated(coordinates: Seq[Coordinates]): Int =
coordinates
.groupMapReduce(identity)(_ => 1)(_ + _)
.values
.filter(_ > 1)
.size
val overlappingPoints = countDuplicated(lines.flatMap(_.spannedCoordinates))
println(s"Part 1: $overlappingPoints")
val overlappingPointsIncludingDiagonal = countDuplicated(
lines.flatMap(_.spannedCoordinatesIncludingDiagonal)
)
println(s"Part 2: $overlappingPointsIncludingDiagonal")