misc/haskell/Dice.hs
2018-08-05 18:53:07 +02:00

26 lines
838 B
Haskell
Executable File

#!/usr/bin/env nix-script
#!>haskell
{- Mathematical way to convert a diceware number. -}
import Data.List (elemIndex)
-- | Convert a decimal numeral n into k-adic base system.
--
-- \boldsymbol{A}_k(n) = \sum_{j=0}^{m-1} 10^j \ [1 + \delta_j \mod k]
-- where m = \bigl \lfloor \log_k [n(k-1)+1] \bigr \rfloor
-- \delta_j = \left \lfloor\frac{n(k-1)+1-k^m}{k^j(k-1)} \right \rfloor
a :: Int -> Int -> Int
a k n = sum [(1 + (d j) `mod` k) * 10^j | j <- [0..m-1]]
where
m = floor $ logBase k' (n'*(k'-1) + 1)
d j = (n*(k-1) + 1 - k^m) `div` ((k-1) * k^j)
(k', n') = (fromIntegral k, fromIntegral n)
interact' :: (String -> String) -> IO ()
interact' f = interact (unlines . map f . lines)
main :: IO ()
main = interact' (show . d . read) where
d = flip elemIndex $ map (a 6 . (+1555)) [0..7775]