Skip to content

Commit

Permalink
Optimize rock rolling in 2023 day 14
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 14, 2023
1 parent cf500a2 commit 4693d47
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/main/scala/eu/sim642/adventofcode2023/Day14.scala
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
package eu.sim642.adventofcode2023

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

object Day14 {

def rollLeft(row: Vector[Char]): Vector[Char] = {

def rollOne(row: List[Char]): List[Char] = row match {
case Nil => Nil
case _ :: Nil => row
case '.' :: 'O' :: newColumn => 'O' :: rollOne('.' :: newColumn)
case prev :: newColumn => prev :: rollOne(newColumn)
def helper(empty: Int, row: List[Char]): List[Char] = row match {
case '.' :: newRow => helper(empty + 1, newRow) // remember . for following O
case 'O' :: newRow => 'O' :: helper(empty, newRow) // put O at first remembered .
case '#' :: newRow => List.fill(empty)('.') ::: '#' :: helper(0, newRow) // materialize .-s and start over
case Nil => List.fill(empty)('.') // materialize .-s at the end
case _ :: _ => throw new IllegalArgumentException("illegal cell")
}

NaiveCycleFinder.find(row.toList, rollOne).cycleHead.toVector // TODO: simpler fixpoint finding?
helper(0, row.toList).toVector
}

def rollNorth(grid: Grid[Char]): Grid[Char] = grid.transpose.map(rollLeft).transpose
Expand Down

0 comments on commit 4693d47

Please sign in to comment.