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
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;
}
}
}
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
.
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.
You probably want to use something like the Fisher-Yates shuffle.