Skip to content

Commit

Permalink
Solve 2023 day 14 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 14, 2023
1 parent f82f64f commit 63522f9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/main/scala/eu/sim642/adventofcode2023/Day14.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package eu.sim642.adventofcode2023

import eu.sim642.adventofcodelib.Grid
import eu.sim642.adventofcodelib.cycle.NaiveCycleFinder
import eu.sim642.adventofcodelib.cycle.{NaiveCycleFinder, NaiverCycleFinder}

object Day14 {

Expand Down Expand Up @@ -87,12 +87,39 @@ object Day14 {
.sum
}

def rollNorth(grid: Grid[Char]): Grid[Char] = grid.transpose.map(rollColumn).transpose
def rollWest(grid: Grid[Char]): Grid[Char] = grid.map(rollColumn)
def rollSouth(grid: Grid[Char]): Grid[Char] = rollNorth(grid.reverse).reverse
def rollEast(grid: Grid[Char]): Grid[Char] = rollWest(grid.map(_.reverse)).map(_.reverse)

def rollCycle(grid: Grid[Char]): Grid[Char] =
rollEast(rollSouth(rollWest(rollNorth(grid))))

def rollCycles(grid: Grid[Char], cycles: Long = 1000000000L): Grid[Char] = {
val cycle = NaiverCycleFinder.find(grid, rollCycle)
// TODO: Long cycle indexing
//cycle(cycles)
val shortI = (cycles - cycle.stemLength) % cycle.cycleLength
cycle(cycle.stemLength + shortI.toInt)
}

def totalLoad2(grid: Grid[Char], cycles: Long = 1000000000L): Int = {
rollCycles(grid, cycles)
.transpose
.map(_.reverse.zipWithIndex.map({
case ('O', i) => i + 1
case _ => 0
}).sum)
.sum
}


def parseGrid(input: String): Grid[Char] = input.linesIterator.map(_.toVector).toVector

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

def main(args: Array[String]): Unit = {
println(totalLoad(parseGrid(input)))
println(totalLoad2(parseGrid(input)))
}
}
8 changes: 8 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2023/Day14Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,12 @@ class Day14Test extends AnyFunSuite {
test("Part 1 input answer") {
assert(totalLoad(parseGrid(input)) == 112048)
}

test("Part 2 examples") {
assert(totalLoad2(parseGrid(exampleInput)) == 64)
}

test("Part 2 input answer") {
assert(totalLoad2(parseGrid(input)) == 105606)
}
}

0 comments on commit 63522f9

Please sign in to comment.