Re: random numbers

new topic     » goto parent     » topic index » view thread      » older message » newer message

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


new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu