2

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

1
  • 2
    Hint: create an array with sequential values from 0 to 20 and then shuffle it, this will guarantee the uniqueness of each element. Commented Feb 23, 2012 at 15:41

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

0

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;
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.