Random Number Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jc1328
    New Member
    • May 2010
    • 2

    #1

    Random Number Question

    Hello,

    I'm using the random generator with 20 numbers. rand() %20+1. Is there a way that the random number can only show up once, so I can go through all 20 numbers before it displays the same number twice?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    No. The way to do that is with a shuffle algorithm. You start with an array of the numbers 1 - 20 then you choose 2 numbers and swap them. You do this lots of times and you end up with an array of the numbers 1 - 20 in a random order but with every number appearing once and only once.

    Comment

    • jkmyoung
      Recognized Expert Top Contributor
      • Mar 2006
      • 2057

      #3
      Another possible way is to generate 20 random double numbers from 0 - 1, and then use their ordering as 1-20.
      eg.
      0.242, 0.425, 0.139, 0.932, 0.495
      ordered is:
      0.138, 0.242, 0.425, 0.495, 0.932
      giving you:
      3, 1, 2, 5, 4

      Comment

      Working...