Day 2: Red-Nosed Reports

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://blocks.programming.dev/ if you prefer sending it through a URL

FAQ

  • VegOwOtenks@lemmy.world
    link
    fedilink
    arrow-up
    5
    ·
    14 days ago

    Haskell

    runningDifference :: [Int] -> [Int]
    runningDifference (a:[]) = []
    runningDifference (a:b:cs) = a - b : (runningDifference (b:cs))
    
    isSafe :: [Int] -> Bool
    isSafe ds = (all (> 0) ds || all (< 0) ds) && (all (flip elem [1, 2, 3] . abs) ds) 
    
    isSafe2 :: [Int] -> Bool
    isSafe2 ds = any (isSafe2') (zip [0..length ds] (cycle [ds]))
    
    isSafe2' (i, ls) = isSafe . runningDifference $ list
            where
                    list = dropIndex i ls
    
    dropIndex _ []     = []
    dropIndex 0 (a:as) = dropIndex (-1) as
    dropIndex i (a:as) = a : dropIndex (i - 1) as
    
    main = do
            c <- getContents
            let reports = init . lines $ c
            let levels  = map (map read . words) reports :: [[Int]]
            let differences = map runningDifference levels
            let safety = map isSafe differences
            let safety2 = map isSafe2 levels
    
            putStrLn . show . length . filter (id) $ safety
            putStrLn . show . length . filter (id) $ safety2
    
            return ()
    

    Took me way too long to figure out that I didn’t have to drop one of them differences but the initial Number