From 82954afc2afa139c501f08875cb3d8b925be16e5 Mon Sep 17 00:00:00 2001 From: Simmo Saan Date: Sun, 3 Dec 2023 09:25:32 +0200 Subject: [PATCH] Solve 2023 day 3 part 2 --- .../eu/sim642/adventofcode2023/Day3.scala | 21 +++++++++++++++++++ .../eu/sim642/adventofcode2023/Day3Test.scala | 8 +++++++ 2 files changed, 29 insertions(+) diff --git a/src/main/scala/eu/sim642/adventofcode2023/Day3.scala b/src/main/scala/eu/sim642/adventofcode2023/Day3.scala index f0c3fb16..e1760a82 100644 --- a/src/main/scala/eu/sim642/adventofcode2023/Day3.scala +++ b/src/main/scala/eu/sim642/adventofcode2023/Day3.scala @@ -10,6 +10,8 @@ object Day3 { def isSymbol(c: Char): Boolean = c != '.' && !c.isDigit + def isGear(c: Char): Boolean = c == '*' + private val numberRegex = """\d+""".r def iteratePartNumbers(schematic: Schematic): Iterator[Int] = { @@ -25,6 +27,24 @@ object Day3 { def sumPartNumbers(schematic: Schematic): Int = iteratePartNumbers(schematic).sum + def sumGearRatios(schematic: Schematic): Int = { + val schematicBox = Box(Pos.zero, Pos(schematic(0).length - 1, schematic.length - 1)) + + val gears = for { + (row, y) <- schematic.iterator.zipWithIndex + m <- numberRegex.findAllMatchIn(row) + box = Box(Pos(m.start, y) - Pos(1, 1), Pos(m.end - 1, y) + Pos(1, 1)) + gearPos <- box.iterator + if schematicBox.contains(gearPos) && isGear(schematic(gearPos.y)(gearPos.x)) + } yield gearPos -> m.toString().toInt + + gears.toSeq + .groupMap(_._1)(_._2) // TODO: groupMap to IteratorImplicits + .filter(_._2.size == 2) + .map(_._2.product) + .sum + } + def parseSchematic(input: String): Schematic = input.linesIterator.toVector @@ -32,5 +52,6 @@ object Day3 { def main(args: Array[String]): Unit = { println(sumPartNumbers(parseSchematic(input))) + println(sumGearRatios(parseSchematic(input))) } } diff --git a/src/test/scala/eu/sim642/adventofcode2023/Day3Test.scala b/src/test/scala/eu/sim642/adventofcode2023/Day3Test.scala index 147fc954..f5b68cf9 100644 --- a/src/test/scala/eu/sim642/adventofcode2023/Day3Test.scala +++ b/src/test/scala/eu/sim642/adventofcode2023/Day3Test.scala @@ -24,4 +24,12 @@ class Day3Test extends AnyFunSuite { test("Part 1 input answer") { assert(sumPartNumbers(parseSchematic(input)) == 521515) } + + test("Part 2 examples") { + assert(sumGearRatios(parseSchematic(exampleInput)) == 467835) + } + + test("Part 2 input answer") { + assert(sumGearRatios(parseSchematic(input)) == 69527306) + } }