Skip to content

Instantly share code, notes, and snippets.

@sajith
Created February 25, 2016 13:40
Show Gist options
  • Save sajith/195068131efd4410d888 to your computer and use it in GitHub Desktop.
Save sajith/195068131efd4410d888 to your computer and use it in GitHub Desktop.
module RandomStr4 where
-- uses `random` package
import Data.List as L
import Data.Text as T
import System.Random (RandomGen, newStdGen, randomRIO, randomRs)
------------------------------------------------------------------------
newToken :: IO Text
newToken = do
g <- newStdGen
newToken' g
newToken' :: RandomGen g => g -> IO Text
newToken' g = fmap T.pack $ scramble $ L.concat [p1, p2, p3]
where
p1 = makeStr 4 ('A', 'Z')
p2 = makeStr 4 ('a', 'z')
p3 = makeStr 4 ('0', '9')
makeStr :: Int -> (Char, Char) -> String
makeStr len range = L.take len $ randomRs range g
-- TODO: benchmark this.
scramble :: String -> IO String
scramble [] = return []
scramble xs = do
n <- randomRIO (0, L.length xs - 1)
let e = xs !! n
result <- scramble (L.delete e xs)
return (e:result)
allUnique :: IO Bool
allUnique = do
xs <- mapM (const newToken) [1..1000]
return $ xs == nub xs
main :: IO ()
main = allUnique >>= print
------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment