0

I'm trying to shuffle an array by following order:

  1. user inputs the size of array
  2. user inputs number of times to shuffle
  3. shuffling function should run by selecting two random number(index) and switching the value of indices. For example, if I made my array arr[10], the fuction should pick two random numbers in range 0~9 and switch positions.
  4. If the user typed 2 in step2, the function should repeat picking two random indices 2 times.

I tried, but something seems wrong(the two numbers are repeatedly identical). How can I get real random numbers?

void shuffle(int arr[], int size) {
    srand(time(NULL));
    int temp, rand1, rand2;

    rand1 = rand() % size;
    rand2 = rand() % size;

    temp = arr[rand1];
    arr[rand1] = arr[rand2];
    arr[rand2] = temp;
}

void total_shuffle(int arr[], int size, int num) {
    for (int i = 0; i < num; i++)
        shuffle(arr, size);
}
oliveTree
  • 7
  • 3
  • 1
    [`srand` should be called exactly once, typically as the first line in `main`](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once). – user3386109 Dec 22 '20 at 16:33

1 Answers1

1

You're seeding the (P)RNG multiple times, most likely with the same value as time() returns seconds, ergo the sequence produced by rand() will be the same, unless your program takes multiple seconds to run, or spans across a one-second boundary. Only call srand() once in your application.

vmt
  • 832
  • 6
  • 16