[email protected]
[Top] [All Lists]

[Haskell-cafe] Strange random choice algorithm

Subject: [Haskell-cafe] Strange random choice algorithm
From: michael rice
Date: Sat, 30 Jan 2010 11:59:08 -0800 PST
I'm not sure where I got this PICK function from, and don't understand why it's written as it is, so I wanted to test it for randomness. It seems random enough. But if I understand the algorithm correctly, instead of selecting one of the elements from the list, it eliminates all the elements but one and that's the value it returns. Seems like a roundabout way of doing it. Comments?

Also, is there a more direct way of printing an array?

Output below.

Michael

=================

import System.Random
import Data.Array.IO

pick :: [a] -> IO a
pick []     = undefined
pick [x]    = do return x
pick (x:xs) = pick' x xs (2 :: Int)

pick' :: (Num p, Random p) => t -> [t] -> p -> IO t
pick' curr []          _    = do return curr
pick' curr (next:rest) prob
  = do r <- getStdRandom (randomR (1,prob))
       let curr' = if r == 1 then next else curr
       pick' curr' rest (prob+1)

main = do arr <- newArray (1,9) 0 :: IO (IOArray Int Int)
          doLoop arr [1,2,3,4,5,6,7,8,9] 0
         
doLoop arr z k = do p <- pick z
                    a <- readArray arr p
                    writeArray arr p (a+1)
                    if k > 10000
                      then do
                        v <- readArray arr 1
                        print v
                        v <- readArray arr 2
                        print v
                        v <- readArray arr 3
                        print v
                        v <- readArray arr 4
                        print v
                        v <- readArray arr 5
                        print v
                        v <- readArray arr 6
                        print v
                        v <- readArray arr 7
                        print v
                        v <- readArray arr 8
                        print v
                        v <- readArray arr 9
                        print v
                      else do
                        doLoop arr z (k+1)

===============

[[email protected] ~]$ runhaskell array1.hs
1110
1117
1080
1169
1112
1119
1137
1084
1074
[[email protected] ~]$


_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe
<Prev in Thread] Current Thread [Next in Thread>