Created
December 14, 2015 04:36
-
-
Save sbenhaim/071d9ee6f4907eb08192 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Prelude | |
import Text.Regex | |
import qualified Data.HashMap.Strict as HashMap | |
type Board = HashMap.HashMap Int (HashMap.HashMap Int Bool) | |
type Coord = (Int,Int) | |
getCoords :: Coord -> Coord -> [Coord] | |
getCoords (sx,sy) (ex,ey) = [ (x,y) | x <- [sx..ex], y <- [sy..ey] ] | |
rx :: Regex | |
rx = mkRegex "(turn on|turn off|toggle) ([0-9]+),([0-9]+) through ([0-9]+),([0-9]+)" | |
parse :: String -> (String, Coord, Coord) | |
parse s = let (Just [cmd, sx, ex, sy, ey]) = matchRegex rx s | |
in (cmd, (read sx, read ex), (read sy, read ey)) | |
emptyBoard :: Int -> Board | |
emptyBoard n = HashMap.fromList $ take n [ y | y <- zip [0..] (repeat row) ] | |
where row = HashMap.fromList $ take n [ x | x <- zip [0..] (repeat False) ] | |
updateBoard :: String -> Board -> [Coord] -> Board | |
updateBoard cmd board coords = foldr fy board coords | |
where fy (x,y) b = HashMap.adjust (\v -> HashMap.adjust (fx cmd) x v) y b | |
fx "turn on" = const True | |
fx "turn off" = const False | |
fx "toggle" = not | |
invokeCommand s board = let (cmd, b, e) = parse s in updateBoard cmd board (getCoords b e) | |
main = do text <- readFile "a6.txt" | |
let result = foldr invokeCommand (emptyBoard 1000) (lines text) in | |
print $ length [ x | y <- HashMap.elems result, x <- HashMap.elems y, x ] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment