Skip to content

Commit

Permalink
Solve 2023 day 3 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 3, 2023
1 parent 6aa236d commit 82954af
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/main/scala/eu/sim642/adventofcode2023/Day3.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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] = {
Expand All @@ -25,12 +27,31 @@ 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

lazy val input: String = io.Source.fromInputStream(getClass.getResourceAsStream("day3.txt")).mkString.trim

def main(args: Array[String]): Unit = {
println(sumPartNumbers(parseSchematic(input)))
println(sumGearRatios(parseSchematic(input)))
}
}
8 changes: 8 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2023/Day3Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 82954af

Please sign in to comment.