56 lines
1.4 KiB
Haskell
56 lines
1.4 KiB
Haskell
import Debug.Trace
|
|
import Data.Maybe
|
|
|
|
traceOut :: Show a => a -> a
|
|
traceOut x = traceShow x x
|
|
|
|
data Shift = Shift Int
|
|
|
|
instance Show Shift where
|
|
show (Shift x) = show x
|
|
|
|
addFirst :: [[a]] -> a -> [[a]]
|
|
addFirst [] x = [[x]]
|
|
addFirst (y:ys) x = ([x] ++ y) : ys
|
|
|
|
split :: [Char] -> [Char] -> [[Char]]
|
|
split _ [] = []
|
|
split delims (x:xs)
|
|
| elem x delims = [[]] ++ split delims xs
|
|
| otherwise = addFirst (split delims xs) x
|
|
|
|
iterateFrom :: [a -> a] -> a -> [a]
|
|
iterateFrom [] x = [x]
|
|
iterateFrom (f:fs) x = x : (iterateFrom fs (f x))
|
|
|
|
iterateWith :: (a -> b -> b) -> [a] -> b -> [b]
|
|
iterateWith f [] b = [b]
|
|
iterateWith f (a:as) b = b : iterateWith f as (f a b)
|
|
|
|
parseShift :: String -> Maybe Shift
|
|
parseShift ('L':xs) = Just $ Shift (-(read xs))
|
|
parseShift ('R':xs) = Just $ Shift (read xs)
|
|
parseShift _ = Nothing
|
|
|
|
parseFile :: String -> Maybe [Shift]
|
|
parseFile = sequence . map parseShift . split ['\n']
|
|
|
|
toFunc :: Shift -> (Int -> Int)
|
|
toFunc (Shift x) = (+x)
|
|
|
|
solve1 :: [Shift] -> Int
|
|
solve1 shifts = length $ filter (==0) $ map (`mod` 100) $ iterateFrom (map toFunc shifts) 50
|
|
|
|
expandShift :: Shift -> [Shift]
|
|
expandShift (Shift x) = take (abs x) $ repeat (Shift (signum x))
|
|
|
|
solve2 :: [Shift] -> Int
|
|
solve2 = solve1 . foldl (++) [] . map expandShift
|
|
|
|
main = do
|
|
fileinp <- readFile "input.txt"
|
|
let shifts = fromJust $ parseFile fileinp
|
|
let solved1 = solve1 shifts
|
|
let solved2 = solve2 shifts
|
|
print solved1
|
|
print solved2
|