Reputation: 351
Is there any function or method to randomly choose a number (or 2 numbers or more) from an array?
Upvotes: 3
Views: 15785
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
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
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
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
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
Reputation: 4985
int RandomElement(int *array, int size)
{
return array[ rand() % size ];
}
if you accept rand as a random number generator.
Upvotes: 2
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