tags:

views:

142

answers:

8

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

+3  A: 

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.

Péter Török
Just be careful to make sure you're giving an equal probability to each element. Something like floor(rand(0..1) * n) should do the trick.
bshields
+2  A: 
int RandomElement(int *array, int size)
{
   return array[ rand() % size ];     
}

if you accept rand as a random number generator.

corn3lius
+1  A: 
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.

Justin Ardini
+7  A: 

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.

Mark B
+1  A: 

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.

Alexandre C.
+1  A: 

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];
torak
+3  A: 
  #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;
  } 
Prasoon Saurav
A: 

Thanks Guys !!!

When responding you should either respond via comment, OR edit your question.
CheesePls