I need to extract 4 different random numbers from an array, excluding some index values. For example, in the code bellow I need to exclude 2 and 3.
Well, no problem, I create a lookup table containing only with the values I need, then 'random_number' +1, + 2, + 5... will give me the other 3 numbers. Won't work... because adding different numbers to a random number will give 2 or 3 at some point.
Why not generate 4 separate random numbers from the pool? There won't a 2 or 3, but especially from a small lookup table there will be duplicate random numbers...
I don't want to exclude those unwanted values from the array because this will mess with index calculations.
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <vector>
int main()
{
static int rand_pool[]{0,1,4,5,6,7,8,9};
std::string years[] = {"2001", "2002", "2003", "2004","2005","2006", "2007", "2008", "2009", "2010"};
srand((int)time(0));
int random_number = rand_pool[rand() % 8];
std::vector<std::string> random_years = {years[random_number], years[1+random_number], years[2+random number}, years[3+random number};
std::vector<std::string>::iterator it;
it = random_years.begin();
for (it = random_years.begin(); it < random_years.end(); it++)
std::cout << "\n" << *it << "\n";
}
Aucun commentaire:
Enregistrer un commentaire