blob: 60e5c1735c334419e61ca6ff42dc0290a7ba28bc (
plain)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
-- requires cabal install --lib megaparsec parser-combinators unordered-containers
module Main (main) where
import Control.Monad (void, when)
import Data.Functor
import Data.List qualified as L
import Data.Map qualified as M
import Data.Set qualified as S
import Data.Void (Void)
import Text.Megaparsec
import Text.Megaparsec.Char
import System.Exit (die)
import Debug.Trace
exampleExpectedOutput = [Two, Equal, Minus, One, Equal, Zero] --"2=-1=0"
data Digit = Equal | Minus | Zero | One | Two deriving (Eq, Ord)
instance Show Digit where
show Equal = "="
show Minus = "-"
show Zero = "0"
show One = "1"
show Two = "2"
type Snafu = [Digit]
type Input = [Snafu]
type Parser = Parsec Void String
parseDigit :: Parser Digit
parseDigit = (char '2' $> Two)
<|> (char '1' $> One)
<|> (char '0' $> Zero)
<|> (char '-' $> Minus)
<|> (char '=' $> Equal)
parseInput' :: Parser Input
parseInput' = some (some parseDigit <* eol) <* eof
parseInput :: String -> IO Input
parseInput filename = do
input <- readFile filename
case runParser parseInput' filename input of
Left bundle -> die $ errorBundlePretty bundle
Right input' -> return input'
snafuToInt :: Snafu -> Int
snafuToInt = L.foldl' snafuToInt' 0
where
snafuToInt' :: Int -> Digit -> Int
snafuToInt' acc Equal = acc * 5 - 2
snafuToInt' acc Minus = acc * 5 - 1
snafuToInt' acc Zero = acc * 5
snafuToInt' acc One = acc * 5 + 1
snafuToInt' acc Two = acc * 5 + 2
intToSnafu :: Int -> Snafu
intToSnafu = intToSnafu' []
where
intToSnafu' :: Snafu -> Int -> Snafu
intToSnafu' acc 0 = acc
intToSnafu' acc num = let (d, m) = (num + 2) `divMod` 5
next = case m of
0 -> Equal
1 -> Minus
2 -> Zero
3 -> One
4 -> Two
in intToSnafu' (next : acc) d
compute :: Input -> Snafu
compute = intToSnafu . sum . map snafuToInt
main :: IO ()
main = do
example <- parseInput "example"
let exampleOutput = compute example
when (exampleOutput /= exampleExpectedOutput) (die $ "example failed: got " ++ show exampleOutput ++ " instead of " ++ show exampleExpectedOutput)
input <- parseInput "input"
print . concatMap show $ compute input
|