lakshmen
lakshmen

Reputation: 29064

how to create an array of non-repeated rand numbers

I would like to create a array having 21 values between 0 to 20.I would like them to be in random and at the same time non-repeated.

I know how to create a random number between 0 to 20.

0 + rand()/(RAND_MAX/(20-0+1)+1)

But i don't know how to create those numbers such that it is not repeated comparing to previous numbers

Upvotes: 2

Views: 305

Answers (4)

lakshmen
lakshmen

Reputation: 29064

I was actually creating 2-dimensional array with values between 0 to 20. after refering to @Oli's ans. I wrote my answer:

int arr[2][6] = {{0,1,2,3,4,5,6}, {7,8,9,10,11,12,13},{14,15,16,17,18,19,20}};
void rearrange_num(int *p)
{
  int temp = 0;
  for(int i = numRows -1 ; i > 0 ; i--)
  {
    for (int j = numCols-1;j>0; j--)
    {
          k = 0 + rand()/(RAND_MAX/(2-0+1)+1);
          l= 0 + rand()/(RAND_MAX/(6-0+1)+1);
          temp = p[i][j]; 
          p[i][j] = p[k][l];
          p[k][l] = temp;
    }
  }
}

Upvotes: 0

Mister Smith
Mister Smith

Reputation: 28158

You can use a Set<Integer> to add rands until the size is 20, then dump to an array.

If you need performance, use Guava's HashSet or Trove's TIntSet.

Upvotes: 0

Adam S
Adam S

Reputation: 3125

It sounds like you're making it harder than necessary. Why don't you create an array of the numbers 1-20, and then randomize it through a shuffle.

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272457

You probably want to use something like the Fisher-Yates shuffle.

Upvotes: 5

Related Questions