From 9c8d506500086e8584387782bc8978d13ffced02 Mon Sep 17 00:00:00 2001 From: Neil Smith Date: Sun, 18 Dec 2016 11:19:23 +0000 Subject: [PATCH] Added version of day 18 that uses a fold. It's more complex and slower. --- advent18.hs | 2 +- advent18f.hs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 advent18f.hs diff --git a/advent18.hs b/advent18.hs index a96251a..e7c304f 100644 --- a/advent18.hs +++ b/advent18.hs @@ -1,4 +1,4 @@ -import Data.List (iterate, tails) +import Data.List (tails) -- input = "..^^." -- input = ".^^.^.^^^^" diff --git a/advent18f.hs b/advent18f.hs new file mode 100644 index 0000000..f643ff5 --- /dev/null +++ b/advent18f.hs @@ -0,0 +1,48 @@ +import Data.List (tails) + +-- input = "..^^." +-- input = ".^^.^.^^^^" +input = "^.^^^.^..^....^^....^^^^.^^.^...^^.^.^^.^^.^^..^.^...^.^..^.^^.^..^.....^^^.^.^^^..^^...^^^...^...^." + +main :: IO () +main = do + part1 + part2 + +part1 :: IO () +part1 = print $ fst $ foldl nextRowFold (countSafe row, row) [2..40] + where row = readRow input + +part2 :: IO () +part2 = print $ fst $ foldl nextRowFold (countSafe row, row) [2..400000] + where row = readRow input + +readRow :: String -> [Bool] +readRow = map (=='^') + +showRow :: [Bool] -> String +showRow = map (\c -> if c then '^' else '.') + +extended :: [Bool] -> [Bool] +extended row = [False] ++ row ++ [False] + +nextRow :: [Bool] -> [Bool] +nextRow = map (isTrap) . segments . extended + +nextRowFold :: (Int, [Bool]) -> Int -> (Int, [Bool]) +nextRowFold (n, row) _ = (n + countSafe newRow, newRow) + where newRow = nextRow row + +countSafe :: [Bool] -> Int +countSafe = length . filter (not) + +segments :: [a] -> [[a]] +segments = filter ((==3) . length) . map (take 3) . tails + +isTrap :: [Bool] -> Bool +isTrap segment + | segment == [True, True, False] = True + | segment == [False, True, True] = True + | segment == [True, False, False] = True + | segment == [False, False, True] = True + | otherwise = False -- 2.34.1