From: Neil Smith Date: Sun, 18 Dec 2016 11:19:23 +0000 (+0000) Subject: Added version of day 18 that uses a fold. It's more complex and slower. X-Git-Url: https://git.njae.me.uk/?a=commitdiff_plain;h=9c8d506500086e8584387782bc8978d13ffced02;p=advent-of-code-16.git Added version of day 18 that uses a fold. It's more complex and slower. --- 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