I'm making a simple script that generates 8 random values from 0 to 7 and stores them into an array named random_numbers
.
This is my try:
int main(int argc, char** argv) {
int random_numbers[8];
srand((unsigned)time(NULL));
for (int i = 0; i < 8; i++) {
random_numbers[i] = 1+ rand() % 8;
cout << random_numbers[i] << endl;
}
return 0;
}
This gives me repeated values. I would like to have random_numbers
filled of random values from 0 to 7, but without any repeated numbers.
How can I do that?
Since you are using c++ any way I modified you code a bit more. Use vector instead of array, this should make your life easier, and this generates 0-7 in a random order without duplicates:
compile with
-std=c++0x
try this code:
Generate the numbers 0 through 7, then shuffle them. Assuming this is actually C++, not C (because of the
cout
), usestd::random_shuffle
:Be warned: cppreference.com states that "The random number generator is implementation-defined, but the function
std::rand
is often used." I've seeded that withstd::srand
, but apparently that's not completely portable.