Choose a number from an array

Is there any function or method for randomly selecting a number (or 2 numbers or more) from an array?

+3
source share
7 answers

Depending on how many digits you need, the size of the array and whether the array should keep its order, you can use std::random_shuffleto change the order of the array, and then just loop from 0..n-1 to get n random numbers. This works better if you want to get many numbers relative to the length of the array.

If it does not fit, you can just use srand()and rand() % nas an index into the array to get a pretty good approximation of a random selection.

+9

n 0..n-1, , .

+3
int RandomElement(int *array, int size)
{
   return array[ rand() % size ];     
}

rand .

+2
randomElement = arr[rand() % ARRAY_SIZE];

. Boost.Random, - , .

+2

rand()% n , , () ( , ).

Better ((double) rand () / MAX_RAND) * n if you can afford the conversion. Or use a random generator whose low bits are known to be random and deviate on the low bits of log n.

+1
source

If you want to select two random numbers from an array, without reusing the same number, it will work

int array[SIZE];

i = rand() % SIZE;
rand1 = array[i];
j = 1 + rand() % (SIZE - 2);
rand2 = array[(i + j) % SIZE];
+1
source
  #include<iostream>
  #include<cstdlib>

  template<typename T,size_t n>
  T randElem(T (&a)[n])
  {

        return a[rand() % n];
  }


  int main()
  {
      int a[]={1,2,3,4,5};

      int n=randElem<int>(a);
      std::cout<<n;
  } 
+1
source

Source: https://habr.com/ru/post/1751396/


All Articles