this post was submitted on 05 Dec 2024
26 points (100.0% liked)

Advent Of Code

987 readers
14 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

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

you are viewing a single comment's thread
view the rest of the comments
[–] VegOwOtenks@lemmy.world 2 points 3 weeks ago* (last edited 3 weeks ago)

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