Funky
Funky

Reputation: 41

C++ Random number generator from a specific array

I want to be able to generate random numbers from a specific array that I will place. For example: I want to generate a random number from the array {2,6,4,8,5}. its just that there is no pattern in the array that I want to generate.

I was only able to search how to generate a random number from 1-100 using srand() from the video tutorial https://www.youtube.com/watch?v=P7kCXepUbZ0&list=PL9156F5253BE624A5&index=16 but I don't know how to specify the array that it will search from..

btw, my code is similar to this..

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(int argc, char*argv[])
{
    srand(time(0)); 

    int i =rand()%100+1;
    cout << i << endl; 
    return 0;
}

Upvotes: 3

Views: 1767

Answers (3)

fgrdn
fgrdn

Reputation: 91

generate random index for this arrays:

before you make a random value, let's init 'the system':

srand((unsigned int)time(0)); // somewhere in the beginning of main, for example

then you somewhere initialize you array, let's say like this:

std::vector<int> array;
fillOutArray(array);

you got something like in you first message: {10, 5, 3, 6}

now you want to get a random value from this array (among these 10, 5, 3 or 6):

auto index = rand() % (array.size());
auto yourValue = array[index];

that's just it.

Upvotes: 0

user6760598
user6760598

Reputation: 11

Using modulus to change your output range can introduce a slight bias. See this talk. If this is a concern of yours, consider using the "random" standard library instead since you're using c++.

Upvotes: 0

CppChris
CppChris

Reputation: 1261

Here is a modern C++ way to do it:

#include <array>
#include <random>
#include <iostream>

auto main() -> int
{
    std::array<int, 10> random_numbers = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 };

    std::random_device random_device;
    std::mt19937 engine(random_device());
    std::uniform_int_distribution<int> distribution(0, random_numbers.size() - 1);

    const auto random_number = random_numbers[distribution(engine)];
}

You can read more about the C++ random functionalities from the standard library here: http://www.cplusplus.com/reference/random/

Upvotes: 5

Related Questions