0

Possible Duplicate:
Is this C implementation of Fisher-Yates shuffle correct?

In order to simulate different order of input sequence into my application, I would like to generate a list of randomize sequence for an array input. For example, given an arr[10], the default sequence is 0,1,..,8,9. However, I'd like to manipulate the sequence into random order, for eg, 2,4,5,1,9,0,3,7,8,6.

I think rand() will generate a random value between 0-9, but it doesn't assure that each element is generated at least once. In such case, I am thinking about below pseudo, but is there a better way to generate random input sequence, and assure each number within the given range is generated at least once?

round #1:  
  generate a random number within 0-9.  
    let say 2 is selected  

round #2:  
    generate a random number within 0-1  
    generate a random number within 3-9  
    let say 0 and 4 are selected  

round #3:  
    generate a random number within 1  
    generate a random number within 3  
    generate a random number within 5-9  
    let say 1, 3, 7 are selected  

round #4:  
    generate a random number within 5-6  
    generate a random number within 8-9  

continue until 10 numbers are selected
Community
  • 1
  • 1
twfx
  • 1,664
  • 9
  • 29
  • 56
  • Generate the sequence 0 - 9 and shuffle the array, preferably with Fisher-Yates. – Jon Jul 13 '12 at 07:31

2 Answers2

2

Look at Fisher-Yates shuffle algorithm here for your requirement.

cyber_raj
  • 1,780
  • 1
  • 14
  • 25
1

Here is another approach:

  1. Create array of 10 elements and fill it with the values you want to randomize (0, 1, ..., 9).
  2. Iterate for k from 9 down to 0 and pick a random number index = rand(k).
  3. Swap the element at position k with the element at position index.

At the end your array will contain a random permutation of the original values, which is exactly what you wanted.

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95