Skip to content

Instantly share code, notes, and snippets.

@neotrinity
Last active August 29, 2015 14:04
Show Gist options
  • Save neotrinity/23311239153f5d9008dc to your computer and use it in GitHub Desktop.
Save neotrinity/23311239153f5d9008dc to your computer and use it in GitHub Desktop.
Decryption problem in haskell and python
-- Using folds version
import Data.List
import Data.Maybe
letters = "acdegilmnoprstuw"
getIndexOf :: Char -> String -> Int
getIndexOf x xs = fromMaybe (-1) (elemIndex x xs)
hashacc :: Int -> Char -> Int
hashacc acc x = acc * 37 + (getIndexOf x (letters))
hash :: String -> Int
hash s = foldl hashacc 7 s
decrypt :: Int -> (Maybe (Char, Int))
decrypt n
| n <= 7 = Nothing
| otherwise = Just(char, n')
where char = (letters) !! (n `mod` 37)
n' = n `quot` 37
unhash :: Int -> String
unhash n = reverse $ unfoldr decrypt n
main = do
print $ hash "leepadg"
print $ unhash 910897038977002
LETTERS = "acdegilmnoprstuw"
LETTERSDICT = {x:i for i, x in enumerate(LETTERS)}
def hash(s):
h = 7
for c in s:
h = h * 37 + LETTERSDICT[c]
return h
def unhash(n):
s = []
while n > 7:
char = LETTERS[n % 37]
s.append(char)
n = n // 37
return "".join(reversed(s))
print hash("leepadg")
print unhash(910897038977002)
import Data.List
import Data.Maybe
letters = "acdegilmnoprstuw"
hash' :: String -> Int -> Int
hash' [] h = h
hash' (x:xs) h = let hh = h * 37 + (head $ elemIndices x (letters))
in hash' xs hh
hash :: String -> Int
hash xs = hash' xs 7
decrypt :: Int -> String
decrypt n
| n <= 7 = ""
| otherwise = decrypt n' ++ [char]
where n' = n `quot` 37
char = (letters) !! (n `mod` 37)
main = do
print $ hash "leepadg"
print $ decrypt 910897038977002
@theburningmonk
Copy link

see my fork for a F# version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment