From f4f5d99ee81ae5d0af6a685b182afc3320ab04c7 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Wed, 5 Dec 2018 10:54:57 +0100 Subject: [PATCH] Adding day 3 --- day3/part1.scala | 33 +++++++++++++++++++++++++++++++++ day3/part2.scala | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 day3/part1.scala create mode 100644 day3/part2.scala diff --git a/day3/part1.scala b/day3/part1.scala new file mode 100644 index 0000000..fb13407 --- /dev/null +++ b/day3/part1.scala @@ -0,0 +1,33 @@ +import scala.io.StdIn.readLine + +case class Claim(id: Int, x: Int, y: Int, w: Int, h: Int) { + val xe: Int = x + (w - 1) + val ye: Int = y + (h - 1) + + def getSquares: Seq[(Int, Int)] = + for { + xi <- x to xe + yi <- y to ye + } yield (xi, yi) +} + +object Claim { + def apply(input: String): Claim = + "#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)".r.findFirstMatchIn(input).map { + m => Claim(m.group(1).toInt, m.group(2).toInt, m.group(3).toInt, m.group(4).toInt, m.group(5).toInt) + }.get +} + +val input = Iterator + .continually(readLine) + .takeWhile(_ != null) + .map(Claim.apply) + +val res = input + .flatMap(_.getSquares) + .foldLeft(Map.empty[(Int, Int), Int]) { + (acc, sq) => acc + (sq -> (acc.getOrElse(sq, 0) + 1)) + } + .count(_._2 > 1) + +println(res) diff --git a/day3/part2.scala b/day3/part2.scala new file mode 100644 index 0000000..6a2e174 --- /dev/null +++ b/day3/part2.scala @@ -0,0 +1,35 @@ +import scala.io.StdIn.readLine + +case class Claim(id: Int, x: Int, y: Int, w: Int, h: Int) { + val xe: Int = x + (w - 1) + val ye: Int = y + (h - 1) + + def getSquares: Seq[((Int, Int), Int)] = + for { + xi <- x to xe + yi <- y to ye + } yield ((xi, yi) -> id) +} + +object Claim { + def apply(input: String): Claim = + "#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)".r.findFirstMatchIn(input).map { + m => Claim(m.group(1).toInt, m.group(2).toInt, m.group(3).toInt, m.group(4).toInt, m.group(5).toInt) + }.get +} + +val claims = Iterator + .continually(readLine) + .takeWhile(_ != null) + .map(Claim.apply) + .toList + +val fabric = claims + .flatMap(_.getSquares) + .foldLeft(Map.empty[(Int, Int), Set[Int]]) { + (acc, sq) => acc + (sq._1 -> (acc.getOrElse(sq._1, Set.empty[Int]) + sq._2)) + } + +val overlapping = fabric.filter(_._2.size > 1).values.flatten.toSet + +println(claims.filterNot(c => overlapping.contains(c.id)))