The rand() is deprecated. One should use the tools that are in <random>. That said, what is the largest number that
N % 8
can be? It is not 8. In other words, you can never pick the "I" or 8. Can your loop end in those conditions?
The
goto
should be avoided too. One is better to be a genius, if one wants to use it properly.
Global variables have limitations too.
Now, the approach of drawing the same number multiple times simply to discard it is not efficient. You do know the valid unique values.
Think about a deck of cards. Each card is unique. If you draw two cards from the deck, what is the chance that they are identical? 0
How do you get a random card? You
shuffle the deck before drawing the cards.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
// shuffle algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::shuffle
#include <array> // std::array
#include <string> // std::string
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock
int main () {
constexpr size_t N = 12;
std::array<std::string,N> foo;
for ( size_t c=0; c<N; ++c ) {
foo[c] = static_cast<char>('A' + c/4) + std::to_string( c%4 );
}
std::cout << "unshuffled elements:";
for ( auto x : foo ) std::cout << ' ' << x;
std::cout << '\n';
// obtain a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
shuffle( foo.begin(), foo.end(), std::default_random_engine(seed) );
std::cout << "shuffled elements:";
for ( auto x : foo ) std::cout << ' ' << x;
std::cout << '\n';
std::cout << "chosen four elements:";
for ( size_t x=0; x<4; ++x ) std::cout << ' ' << foo[x];
std::cout << '\n';
return 0;
}
|