Day 5: Print Queue
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://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
Haskell
It’s more complicated than it needs to be, could’ve done the first part just like the second.
Also it takes one second (!) to run it .-.
import Data.Maybe as Maybe import Data.List as List import Control.Arrow hiding (first, second) parseRule :: String -> (Int, Int) parseRule s = (read . take 2 &&& read . drop 3) s replace t r c = if t == c then r else c parse :: String -> ([(Int, Int)], [[Int]]) parse s = (map parseRule rules, map (map read . words) updates) where rules = takeWhile (/= "") . lines $ s updates = init . map (map (replace ',' ' ')) . drop 1 . dropWhile (/= "") . lines $ s validRule (pairLeft, pairRight) (ruleLeft, ruleRight) | pairLeft == ruleRight && pairRight == ruleLeft = False | otherwise = True validatePair rs p = all (validRule p) rs validateUpdate rs u = all (validatePair rs) pairs where pairs = List.concatMap (\ t -> map (head t, ) (tail t)) . filter (length >>> (> 1)) . tails $ u middleElement :: [a] -> a middleElement us = (us !!) $ (length us `div` 2) part1 (rs, us) = sum . map (middleElement) . filter (validateUpdate rs) $ us insertOrderly rs i is = insertOrderly' frontRules i is where frontRules = filter (((== i) . fst)) rs insertOrderly' _ i [] = [i] insertOrderly' rs i (i':is) | any (snd >>> (== i')) rs = i : i' : is | otherwise = i' : insertOrderly' rs i is part2 (rs, us) = sum . map middleElement . Maybe.mapMaybe ((orderUpdate &&& id) >>> \ p -> if (fst p /= snd p) then Just $ fst p else Nothing) $ us where orderUpdate = foldr (insertOrderly rs) [] main = getContents >>= print . (part1 &&& part2) . parse