Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filling an array with random number

Tags:

c++

c

random

I'm trying to fill an array of 20 ints with numbers from 1-20 in random sequence. here's my code:

 int lookup[20]={0}; 
 int array[20]={0};
 srand(time(NULL));
 for(int i=0;i<20;++i){ 
    bool done=false;
    while(!done){
      int n=rand()%20;
      if(lookup[n]==0){
          array[i]=n;
          lookup[n]=1;
          done=true;
      }
    }
 }

I've created a lookup array to check if the random number is not yet chosen and stored it in array. As you can see I've created 2 loops, one for traversing array and the while for choosing the random number. In every while loop iteration the number may reappear and causing another while loop. Is there faster way to do this?

like image 425
James Avatar asked Mar 03 '10 09:03

James


4 Answers

You could fill the array in sequence and then shuffle it. That would prevent having to ever do more than 20 random number generations.

Fisher-Yates shuffle: can be done in O(n) time.

From wikipedia:

Properly implemented, the Fisher–Yates shuffle is unbiased, so that every permutation is equally likely. The modern version of the algorithm is also rather efficient, requiring only time proportional to the number of items being shuffled and no additional storage space.

like image 142
sfg Avatar answered Sep 19 '22 06:09

sfg


Look at std::random_shuffle and std::vector.

like image 44
graham.reeds Avatar answered Sep 21 '22 06:09

graham.reeds


you could fill an array with numbers from 1 to 20 and use std::random_shuffle

note you don't need a vector for that matter a simple array will do.
example :

#include <iostream>
#include <algorithm>

using namespace std;

int main( void )
{
        int array[] = { 0, 1, 2, 3, 4 };

        srand( unsigned( time(NULL) ) );

        random_shuffle(array, array+5);

        for(int i=0; i<5; i++)
                cout << array[i] << endl;

        return 0;
}
like image 23
f4. Avatar answered Sep 22 '22 06:09

f4.


There's the possibility in your code of a very long running loop. If you're inside the while(!done) loop there's no guarantee you'll ever finish. Obviously with an array of 20 elements this won't in practice be an issue but it could cause problems if you scale this up to many thousands of elements.

A more reliable solution would be to fill the array sequentially and then shuffle it afterwards.

like image 21
Dolbz Avatar answered Sep 20 '22 06:09

Dolbz