Re: random numbers

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

Allen Ashby wrote:
> 
> 
> I am trying to generate 52 random numbers 1-52 without duplicating any
> numbers.
> it seems every time I try I get duplications. Does anyone have a
> solution for this.
> 

include misc.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

-- Unit tests
sequence test
if find("--unittest", command_line()) then
  puts(2, "Doing unit testing\n")
  test = Shuffle()
  if length(test) != 52 then
    printf(2, "Length is %d and not 52\n", length(test))
    
  end if
  for i = 1 to length(test) do
    if find(test[i], test[i+1..$]) then
        printf(2, "Dup %d at %d\n", {test[i], i})
    end if
  end for
end if
-- 
Derek Parnell
Melbourne, Australia
Skype name: derek.j.parnell

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

Search



Quick Links

User menu

Not signed in.

Misc Menu