Avión Avión -3 years ago 94
C++ Question

Generate 8 unique random numbers from 0 to 7

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?

Answer Source

Generate the numbers 0 through 7, then shuffle them. Assuming this is actually C++, not C (because of the cout), use std::random_shuffle:

#include <algorithm>
#include <cstdlib>
#include <iostream>

int main()
{
    int a[8] = {0, 1, 2, 3, 4, 5, 6, 7};
    std::srand(unsigned(std::time(0)));

    std::random_shuffle(a, a + 8);

    for (int i=0; i<8; i++)
        std::cout << a[i] << " ";
    std::cout << std::endl;
}

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 with std::srand, but apparently that's not completely portable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download