Re: random numbers
- Posted by c.k.lester <euphoric at c?les?er.com> Nov 22, 2007
- 586 views
Derek Parnell wrote: > function Shuffle() > sequence ShuffledDeck > integer temp > ShuffledDeck = {} > while length(ShuffledDeck) < 52 do > temp = rand(52) > if not find(temp, ShuffledDeck) then > ShuffledDeck &= temp > end if > end while > return ShuffledDeck > end function Wouldn't that possibly take too long generating the last number? You have a 51 out of 52 chance of picking a number the already exists. Nevermind... here's a test:
include misc.e include get.e function Shuffle() sequence ShuffledDeck integer temp ShuffledDeck = {} while length(ShuffledDeck) < 52 do temp = rand(52) if not find(temp, ShuffledDeck) then ShuffledDeck &= temp end if end while return ShuffledDeck end function function shuff() sequence s, n integer r s = {} for t=1 to 52 do s &= t end for n = {} for t=1 to 52 do r = rand(length(s)) -- grab a random position n &= s[r] -- add it to our new sequence s = s[1..r-1] & s[r+1..$] -- remove from available numbers end for return n end function atom c, t sequence test c=0 t = time() + 3 while t > time() do test = Shuffle() c += 1 end while ?c c = 0 t = time() + 3 while t > time() do test = shuff() c += 1 end while ?c if wait_key() then end if