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;
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With