Re: random numbers
- Posted by c.k.lester <euphoric at c?lester.co?> Nov 22, 2007
- 563 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 constant fittytwo = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52} 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 function shuff2() sequence s, n integer r s = repeat(0,52) for t=1 to 52 do s[t] = 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 function shuff3() sequence s, n integer r s = fittytwo 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 puts(1,"Starting test...\n\n") 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 c = 0 t = time() + 3 while t > time() do test = shuff2() c += 1 end while ?c c = 0 t = time() + 3 while t > time() do test = shuff3() c += 1 end while ?c if wait_key() then end if