1 -- Writeup at https://work.njae.me.uk/2022/12/01/advent-of-code-2022-day-1/
9 do dataFileName <- getDataFileName
10 numStrs <- readFile dataFileName
11 let fuels = fmap readSnafu $ lines numStrs
12 putStrLn $ showSnafu $ sum fuels
14 readSnafu :: String -> Int
15 readSnafu cs = foldl' go 0 cs
16 where go acc c = acc * 5 + (snafuValue c)
18 snafuValue :: Char -> Int
24 snafuValue _ = error "Illegal digit in read"
26 showSnafu :: Int -> String
27 showSnafu = packSnafu . toBase5R
29 toBase5R :: Int -> [Int]
31 toBase5R n = (r : (toBase5R k))
32 where (k, r) = n `divMod` 5
34 packSnafu :: [Int] -> String
37 | otherwise = (snafuRep carry) : shown
38 where (carry, shown) = foldl' packSnafuDigit (0, "") digits
40 packSnafuDigit :: (Int, String) -> Int -> (Int, String)
41 packSnafuDigit (carry, acc) d
42 | d' <= 2 = (0, (snafuRep d') : acc)
43 | otherwise = (1, (snafuRep (d' - 5) : acc))
46 snafuRep :: Int -> Char
52 snafuRep _ = error "Illegal number in show"