aoc2021-day10b Haskell/GHC #2 program
source code
-- SPDX-License-Identifier: ISC
-- Copyright (c) 2021 Paolo Martini <mrtnpaolo@protonmail.com>
module Main (main) where
import Data.List (foldl',sort)
import Data.Either (partitionEithers)
import Data.List (foldl')
import Data.Map.Strict qualified as M' (toAscList,fromListWith)
main =
do (corrupted,incomplete) <- partitionEithers <$> getInputLines parse 10
print (part2 incomplete)
parse = go []
where
go seen [] = Right seen -- string is incomplete
go seen@(~(s:rest)) (x:xs)
| open x = go (x:seen) xs
| s == match x = go rest xs
| otherwise = Left x -- string is corrupted
open x = x `elem` "([{<"
match ')' = '('
match ']' = '['
match '}' = '{'
match '>' = '<'
part2 = middle . map (base5 . map score)
where
base5 = foldl' (\a i -> a*5 + i) 0
middle xs = sort xs !! (length xs `div` 2)
score '(' = 1; score ')' = 3
score '[' = 2; score ']' = 57
score '{' = 3; score '}' = 1197
score '<' = 4; score '>' = 25137
-- Utilities
getInput :: (String -> a) -> Int -> IO a
getInput parse day = parse <$> getContents
getInputLines :: (String -> a) -> Int -> IO [a]
getInputLines parse day = getInput (map parse . lines) day
notes, command-line, and program output
NOTES:
Linux
Sun, 23 Jan 2022 16:39:21 GMT
MAKE:
ghc -O2 aoc2021_day10b.hs-2.hs -o app_hs
[1 of 1] Compiling Main ( aoc2021_day10b.hs-2.hs, aoc2021_day10b.hs-2.o )
Linking app_hs ...
0.58s to complete and log all make actions
COMMAND LINE:
./app_hs 0 < aoc2021_day10b-input10000.txt
PROGRAM OUTPUT:
4147221136278686118851251078439942241593032865422495540589075652007224217627158672406548941332753773231145137591607755327259751330408129749234363801432056312168742919300272994666758197001661058825916005929107429822715605939942443473451119156732403958992327362236310858256528168096490885509843074970456349764872605113646021900154182133457634302249036648560726381663678169920580181158091185711536415744289810493158025390014526746339533063857301193312008845372928578055750021478792579394195467723166421532710570596861139275905662620238