I'm trying to solve the whole Advent of Code series in Haskell.
I'm encountering a memory issue while solving the 2015/06 exercise where there is a bunch of instructions to turn on, off and toggle lights on a grid. The goal is to count the number of lit lights at the end.
Given instructions are parsed and stored in a Instruction
type, this is the type definition:
data Instruction = Instruction Op Range deriving Show
data Op = Off | On | Toggle | Nop deriving Show
data Range = Range Start End deriving Show
type Start = Point
type End = Start
data Point = Point Int Int deriving Show
This is the code that calculates the result. I'm trying to abstract over the fact that a light is a Boolean by using a typeclass
gridWidth, gridHeight :: Int
gridWidth = 1000
gridHeight = 1000
initialGrid :: Togglable a => Matrix a
initialGrid = matrix gridWidth gridHeight (const initialState)
instance Monoid Op where
mempty = Nop
instance Semigroup Op where
_ <> On = On
_ <> Off = Off
x <> Nop = x
Off <> Toggle = On
On <> Toggle = Off
Toggle <> Toggle = Nop
Nop <> Toggle = Toggle
class Togglable a where
initialState :: a
apply :: Op -> a -> a
instance Togglable Bool where
initialState = False
apply On = const True
apply Off = const False
apply Toggle = not
apply Nop = id
-- Does the Range of the instruction apply to this matrix coordinate?
(<?) :: Range -> (Int, Int) -> Bool
(<?) (Range start end) (x, y) = let
(Point x1 y1) = start
(Point x2 y2) = end
(mx, my) = (x-1, y-1) -- translate from matrix coords (they start from 1!)
in and [
mx >= min x1 x2, mx <= max x1 x2,
my >= min y1 y2, my <= max y1 y2
]
stepGenerator :: Instruction -> Matrix Op
stepGenerator (Instruction op r) = let
g coord = if r <? coord then op else Nop
in matrix gridWidth gridHeight g
allStepsMatrix :: [Instruction] -> Matrix Op
allStepsMatrix = mconcat.map stepGenerator
finalGrid :: Togglable a => Matrix a -> Matrix Op -> Matrix a
finalGrid z op = fmap apply op <*> z
countOn :: Matrix Bool -> Integer
countOn = toInteger.foldr (\x -> if x then (+1) else id) 0
partA :: Challenge (String -> Integer)
partA = Challenge $ countOn.finalGrid initialGrid.allStepsMatrix.parse
The solution will be the Integer returned by what's inside partA
. parse
works and has type parse :: String -> [Instruction]
The code compiles and runs with small matrices (e.g. 10x10), as soon as I turn gridWidth
and gridHeight
to 1000 I'm faced with a out of memory
error, apparently generating from the allStepsMatrix
function.
Any hint of what could be wrong here? Full code is on GitHub