user336671
user336671

Reputation: 351

Choose a number from an array

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

Upvotes: 3

Views: 15785

Answers (7)

Prasoon Saurav
Prasoon Saurav

Reputation: 92854

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

Upvotes: 1

torak
torak

Reputation: 5802

If you want to select two random numbers from the array, without reusing the same number the following would work

int array[SIZE];

i = rand() % SIZE;
rand1 = array[i];
j = 1 + rand() % (SIZE - 2);
rand2 = array[(i + j) % SIZE];

Upvotes: 1

Justin Ardini
Justin Ardini

Reputation: 9866

randomElement = arr[rand() % ARRAY_SIZE];

This is the simplest approach. You could use the Boost.Random library if you want to do something more complicated, like assign different probabilities to different elements of the array.

Upvotes: 2

Alexandre C.
Alexandre C.

Reputation: 56956

rand() % n is often pretty much non-random, at least with legacy (bad) random generators (there are plenty of them, beware).

Better is ((double)rand() / MAX_RAND) * n if you can afford the conversion. Or use a random generator whose lower bits are known to be random, and do rejection on the lower log n bits.

Upvotes: 1

Mark B
Mark B

Reputation: 96233

Depending on how many numbers you need, the size of the array, and whether the array needs to retain its order, you could use std::random_shuffle to reorder the array and then just loop from 0..n-1 to get n random numbers. This works better when you want to get a lot of numbers relative to the length of the array.

If that doesn't seem appropriate, you can just use srand() and rand() % n as an index into the array to get a pretty good approximation of a random selection.

Upvotes: 8

corn3lius
corn3lius

Reputation: 4985

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

if you accept rand as a random number generator.

Upvotes: 2

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116246

For your array of size n, just generate a random number in the 0..n-1 range, then select the number indexed in the array.

Upvotes: 3

Related Questions