newbie:: getting random Ints

Peter Rooney pt@panix.com
02 Apr 2002 23:00:09 -0500


ketil@ii.uib.no (Ketil Z. Malde) writes:

<snip OP>
> 
> Depending on why you need random numbers, you might want to consider
> using a fixed seed, i.e. 
> 
>         a = randoms (mkStdGen 4711)
> 
> will get you a sequence of "random" numbers.  Of course, it will be
> the same sequence for every run of your program, but in some cases,
> (when you only want arbitrary data, and not necessarily random) this
> won't matter much.
> 
> The advantage is, of course, that you get rid of the IO monad.  I've
> toyed with the idea of using unsafePerformIO (at least to get the
> seed), but haven't quite dared (or needed) to yet. :-)
> 

well, thanks to all for the help. in my case, it was not OK to have
arbitrary data, i needed (pseudo-) random numbers for different runs
of the program.  i want to:

-generate random Ints
-do some arbitrary computations on them to generate a [[Int]]
-compare each [Int] in the list with a list of [Int] known at compile time

the functions below seem to be doing what i need; i'm posting the code
in case it helps other newbies get there a bit faster than i did. any
constructive criticism / pointing out of errors most welcome.

code:

> import Random

> rollDice :: IO Int
> rollDice = getStdRandom (randomR (1,6))
 
> getRandomSeed :: IO Int
> getRandomSeed = do
>                 retval <- rollDice
>                 return retval
 
> getRandomSeedInt :: IO Int -> Int
> getRandomSeedInt x = unsafePerformIO x
 
> getARange :: Int -> Int -> [Int]
> getARange x y  = randomRs (x,y) (mkStdGen (getRandomSeedInt getRandomSeed))
 
> getRandomInt :: Int -> Int
> getRandomInt x = head (take 1 (getARange 0 x ))

output:

Main> take 20 (getARange 0 10)
[5,8,1,8,2,8,9,7,1,4,6,2,5,8,6,2,10,0,7,10]
Main> take 20 (getARange 0 10)
[9,8,9,9,7,2,4,5,1,7,2,2,8,2,5,10,5,3,1,8]


thanks and regards,
peter