Skip to content

Instantly share code, notes, and snippets.

@theburningmonk
Forked from neotrinity/hash_folds.hs
Last active August 29, 2015 14:05
Show Gist options
  • Save theburningmonk/f898223c4b739718e2d0 to your computer and use it in GitHub Desktop.
Save theburningmonk/f898223c4b739718e2d0 to your computer and use it in GitHub Desktop.
open System
let letters = "acdegilmnoprstuw"
let hash : string -> int64 = Seq.fold (fun acc ch -> acc * 37L + int64 (Seq.findIndex ((=) ch) letters)) 7L
let unhash : int64 -> string =
Seq.unfold (function
| n when n <= 7L -> None
| n -> let idx = n % 37L |> int
(letters.[idx], n / 37L) |> Some)
>> (fun chars -> new String(chars |> Seq.toArray |> Array.rev))
// usage
hash "leepadg"
unhash 910897038977002L
-- 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment