Skip to content

Instantly share code, notes, and snippets.

@abedra
Created April 9, 2012 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abedra/2340685 to your computer and use it in GitHub Desktop.
Save abedra/2340685 to your computer and use it in GitHub Desktop.
import Data.List
import Data.Maybe
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
base = length alphabet
encode :: Int -> String
encode 0 = "a"
encode id = map (\x -> alphabet !! x) (reverse (tail (map (\x -> snd x) options)))
where options = takeWhile (/= (0,0)) (iterate (\x -> ((fst x `div` 62), (fst x `mod` 62))) (id,0))
decode :: String -> Int
decode encoded = foldl (\x y -> x * base + fromJust y) 0 (map (\x -> elemIndex x alphabet) encoded)
-- encode 125
-- decode "cb"
-- encode 19158
-- decode "e9a"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment