DEV Community

loading...

Discussion on: Advent of Code 2020 Solution Megathread - Day 3: Toboggan Trajectory

Collapse
erikbackman profile image
Erik Bäckman

Haskell

import Control.Lens ((^?))
import Control.Lens.At (Ixed(ix))
import Data.Maybe (catMaybes, isJust)

matrixLookup :: [[a]] -> (Int, Int) -> Maybe a
matrixLookup m (x, y) = m ^? ix (abs y) . ix (abs x)

slope :: (Int, Int) -> [(Int, Int)]
slope (run, rise) = zip [0,run..] [0,rise..]

charsAlongSlope :: [String] -> (Int, Int) -> [Char]
charsAlongSlope grid (run, rise) = catMaybes
                                 $ takeWhile isJust
                                 $ matrixLookup grid <$> slope (run, rise)

parseInput :: String -> [String]
parseInput = fmap cycle . lines

solveForSlope :: String -> (Int, Int) -> Int
solveForSlope i s = length . filter (== '#') $ charsAlongSlope (parseInput i) s

solveP1 :: String -> Int
solveP1 inp = solveForSlope inp (3, -1)

solveP2 :: String -> Int
solveP2 inp = product (solveForSlope inp <$> slopes)
  where
    slopes = [ (1, -1)
             , (3, -1)
             , (5, -1)
             , (7, -1)
             , (1, -2)
             ]
Enter fullscreen mode Exit fullscreen mode