projects
/
advent-of-code-22.git
/ commitdiff
commit
grep
author
committer
pickaxe
?
search:
re
summary
|
shortlog
|
log
|
commit
| commitdiff |
tree
raw
|
patch
|
inline
| side by side (parent:
2b91cfe
)
Rebuilt as a fold
author
Neil Smith
<NeilNjae@users.noreply.github.com>
Sun, 25 Dec 2022 20:10:27 +0000
(20:10 +0000)
committer
Neil Smith
<NeilNjae@users.noreply.github.com>
Sun, 25 Dec 2022 20:10:27 +0000
(20:10 +0000)
advent25/Main.hs
patch
|
blob
|
history
diff --git
a/advent25/Main.hs
b/advent25/Main.hs
index f6a284f2e2cab80058544b61795de9a6ab0cad85..cc0a464c9fbd83ec28652aaedab4c7fe306ce08f 100644
(file)
--- a/
advent25/Main.hs
+++ b/
advent25/Main.hs
@@
-25,21
+25,23
@@
snafuValue '=' = -2
snafuValue _ = error "Illegal digit in read"
showSnafu :: Int -> String
snafuValue _ = error "Illegal digit in read"
showSnafu :: Int -> String
-showSnafu =
reverse . (packSnafu 0)
. toBase5R
+showSnafu =
packSnafu
. toBase5R
toBase5R :: Int -> [Int]
toBase5R 0 = []
toBase5R n = (r : (toBase5R k))
where (k, r) = n `divMod` 5
toBase5R :: Int -> [Int]
toBase5R 0 = []
toBase5R n = (r : (toBase5R k))
where (k, r) = n `divMod` 5
-packSnafu :: Int -> [Int] -> String
-packSnafu 0 [] = ""
-packSnafu carry [] = [snafuRep carry]
-packSnafu carry (d:ds)
- | d' <= 2 = ((snafuRep d') : (packSnafu 0 ds))
- | otherwise = ((snafuRep (d' - 5)) : (packSnafu 1 ds))
+packSnafu :: [Int] -> String
+packSnafu = snd . foldl' packSnafuDigit (0, "")
+
+packSnafuDigit :: (Int, String) -> Int -> (Int, String)
+packSnafuDigit (carry, acc) d
+ | d' <= 2 = (0, (snafuRep d') : acc)
+ | otherwise = (1, (snafuRep (d' - 5) : acc))
where d' = d + carry
where d' = d + carry
+
snafuRep :: Int -> Char
snafuRep 2 = '2'
snafuRep 1 = '1'
snafuRep :: Int -> Char
snafuRep 2 = '2'
snafuRep 1 = '1'