day13 part 1

part 2 doesn’t work, time to rewrite
This commit is contained in:
Gattix 2022-12-14 00:21:42 +01:00
parent e362e9531e
commit 97024928af

40
2022/day13/day13.hs Normal file
View File

@ -0,0 +1,40 @@
{-# LANGUAGE OverloadedStrings #-}
import Data.List
import Data.List.Split
import Data.Maybe
import qualified Data.Text as T
main :: IO ()
main = do
input <- map lines . splitOn "\n\n" <$> readFile "input"
let toDigit = T.unpack . T.replace "10" ":" . T.pack
print $
sum $ zipWith (*) [1 ..] $ map (fromEnum . isOrdered 0 . map toDigit) input
let divider = ["[[6]]", "[[2]]"]
let sorted = sortBy mySort (divider ++ concat input)
print $ product $ map (+ 1) $ mapMaybe (`elemIndex` sorted) divider
isOrdered :: Int -> [String] -> Bool
isOrdered n [l:ls, r:rs]
| n < 0 && l == ',' = False
| n > 0 && r == ',' = True
| l == r = isOrdered n [ls, rs]
| l == ']' = (r /= ',') || isOrdered (succ n) [ls, r : rs]
| r == ']' = l == ',' && isOrdered (pred n) [l : ls, rs]
| l == '[' = r /= ']' && isOrdered (pred n) [ls, r : rs]
| r == '[' = l == ']' || isOrdered (succ n) [l : ls, rs]
| l == ',' = False
| r == ',' = True
| l > r = False
| l < r = True
| otherwise = False
isOrdered _ [[], _] = True
isOrdered _ [_, []] = False
isOrdered _ _ = True
mySort :: String -> String -> Ordering
mySort x y =
if isOrdered 0 [x, y]
then LT
else GT