Shuffle array in C

前端 未结 7 1933
执念已碎
执念已碎 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:42

    I didn't see it among answers so I propose this solution if it can help anybody:

    static inline void shuffle(size_t n, int arr[])
    {
        size_t      rng;
        size_t      i;
        int         tmp[n];
        int         tmp2[n];
    
       memcpy(tmp, arr, sizeof(int) * n);
        bzero(tmp2, sizeof(int) * n);
        srand(time(NULL));
        i = 0;
        while (i < n)
        {
            rng = rand() % (n - i);
            while (tmp2[rng] == 1)
                ++rng;
            tmp2[rng] = 1;
            arr[i] = tmp[rng];
            ++i;
        }
    }
    

提交回复
热议问题