Shuffle array in C

前端 未结 7 1914
执念已碎
执念已碎 2020-11-22 03:15

I\'m looking for a function in ANSI C that would randomize an array just like PHP\'s shuffle() does. Is there such a function or do I have to write it on my own

7条回答
  •  借酒劲吻你
    2020-11-22 03:44

    The following code ensures that the array will be shuffled based on a random seed taken from the usec time. Also this implements the Fisher–Yates shuffle properly. I've tested the output of this function and it looks good (even expectation of any array element being the first element after shuffle. Also even expectation for being the last).

    void shuffle(int *array, size_t n) {    
        struct timeval tv;
        gettimeofday(&tv, NULL);
        int usec = tv.tv_usec;
        srand48(usec);
    
    
        if (n > 1) {
            size_t i;
            for (i = n - 1; i > 0; i--) {
                size_t j = (unsigned int) (drand48()*(i+1));
                int t = array[j];
                array[j] = array[i];
                array[i] = t;
            }
        }
    }
    

提交回复
热议问题