Skip to content

Commit

Permalink
Solve 2023 day 11 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 11, 2023
1 parent 677b985 commit ff69ce0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/main/scala/eu/sim642/adventofcode2023/Day11.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@ object Day11 {
} yield (galaxy1 manhattanDistance galaxy2) + freeXs.count(x => galaxyMin.x < x && x < galaxyMax.x) + freeYs.count(y => galaxyMin.y < y && y < galaxyMax.y)).sum
}

// TODO: deduplicate
def sumDistances2(galaxies: Seq[Pos], factor: Long = 1000000L): Long = {
val xs = galaxies.map(_.x).toSet
val freeXs = (0 to xs.max).toSet -- xs
val ys = galaxies.map(_.y).toSet
val freeYs = (0 to ys.max).toSet -- ys

(for {
(galaxy1, i) <- galaxies.view.zipWithIndex
galaxy2 <- galaxies.view.drop(i + 1)
galaxyMin = galaxy1 min galaxy2
galaxyMax = galaxy1 max galaxy2
} yield (galaxy1 manhattanDistance galaxy2) + (factor - 1) * freeXs.count(x => galaxyMin.x < x && x < galaxyMax.x) + (factor - 1) * freeYs.count(y => galaxyMin.y < y && y < galaxyMax.y)).sum
}

def parseGalaxies(input: String): Seq[Pos] = {
val grid = input.linesIterator.map(_.toVector).toVector
(for {
Expand All @@ -32,5 +47,6 @@ object Day11 {

def main(args: Array[String]): Unit = {
println(sumDistances(parseGalaxies(input)))
println(sumDistances2(parseGalaxies(input)))
}
}
9 changes: 9 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2023/Day11Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,13 @@ class Day11Test extends AnyFunSuite {
test("Part 1 input answer") {
assert(sumDistances(parseGalaxies(input)) == 9509330)
}

test("Part 2 examples") {
assert(sumDistances2(parseGalaxies(exampleInput), 10) == 1030)
assert(sumDistances2(parseGalaxies(exampleInput), 100) == 8410)
}

test("Part 2 input answer") {
assert(sumDistances2(parseGalaxies(input)) == 635832237682L)
}
}

0 comments on commit ff69ce0

Please sign in to comment.