0

I have a function which uses random_shuffle to generate non-repeating random numbers. I want to call that function n times and have it generate n different list of non-repeating random numbers. I'm pretty sure I have to play with the srand function but I'm not sure how.

// random generator function:
int myrandom (int i) { return std::rand()%i;}

void dealCards();

int main () {
    for (int i=0; i<10; i++) {
        dealCards();
    }

    return 0;
}

void dealCards(){
    std::srand ( unsigned ( std::time(0) ) );
    std::vector<int> myvector;

    int myarray[32];

    // set some values:
    for (int i=1; i<33; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9

    // using myrandom:
    std::random_shuffle ( myvector.begin(), myvector.end(), myrandom);

    std::cout << "myvector contains:";

    std::srand ( unsigned (std::time(0)) );
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it){
        std::cout << ' ' << *it;
    }

    std::cout << '\n' << '\n';

}

solalito
  • 1,189
  • 4
  • 19
  • 34

2 Answers2

1

Here's a srand function to make the result give you some pseudo-random numbers that is widely used:

srand(time(NULL));

You only can seed the random value generator once, so don't place it in a loop.
It simply won't function right if you do.

Chantola
  • 540
  • 1
  • 5
  • 18
1

You should only seed the random generator once.

Move

std::srand ( unsigned ( std::time(0) ) );

into main.

If your function executes in less than one second, you will re-seed the generator with the same seed next time, giving you the same sequence.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82