1

I'm currently using this function to muddle up all items of an array :

void shuffleArray(int *array)
{
    int index;
    int buffer
    int randomIndex;
    srand((int)time(NULL));
    //SIZE is my tab's length
    for(index = 0; index < SIZE - 1; index++)
    {
        randomIndex = (index + rand() / (RAND_MAX / SIZE - index) + 1));
        buffer = array[randomIndex];
        array[randomIndex] = array[index];
        array[index] = buffer;
    }
}

But I've a problem: The first value of my array is always the same as a function of current time.

I'm lost, if you can show me the right way..

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • What exactly do you mean? Do you mean that the sequence of random incices is the same all time? – Codor Dec 23 '14 at 08:09
  • No, only my the first item ! For exemple array : 1 - 2 - 3 - 4 - 5 would be after a shuffle : 2 - 4 - 3 - 1 - 5. 2 would be all the time the first element during a few minutes –  Dec 23 '14 at 08:14
  • 1
    http://stackoverflow.com/questions/7343833/srand-why-call-only-once This might help you – Ashwani Dec 23 '14 at 08:14

1 Answers1

1

srand() gets you the same random number once for a program so thats the problem

srand() — why call it only once?

This can help

Community
  • 1
  • 1
Aditya Kiran
  • 251
  • 1
  • 4
  • 12
  • I've put srand in my main, same result :/ But ty for the advice –  Dec 23 '14 at 09:05
  • 1
    Finally, this worked fine (i've take a lot of time to understand this) : struct timeval t1; gettimeofday(&t1, NULL); srand((int)(t1.tv_usec * t1.tv_sec)); Thanks all, +1 –  Dec 23 '14 at 09:27
  • @AdrienWeidemann: That (using both seconds and microseconds to create a seed value) works after a fashion, though it excludes prime numbers from the list of seed values, but it is still an abuse of the way you're supposed/intended to use `srand()` if you call it multiple times. – Jonathan Leffler Dec 23 '14 at 15:34