how to create an array of non-repeated rand numbers

后端 未结 4 966
时光取名叫无心
时光取名叫无心 2021-01-23 02:57

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

相关标签:
4条回答
  • 2021-01-23 03:00

    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;
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-23 03:09

    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.

    0 讨论(0)
  • 2021-01-23 03:16

    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.

    0 讨论(0)
  • 2021-01-23 03:23

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

    0 讨论(0)
提交回复
热议问题