Shuffle array in C

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

    Here a solution that uses memcpy instead of assignment, so you can use it for array over arbitrary data. You need twice the memory of original array and the cost is linear O(n):

    void main ()
    {
        int elesize = sizeof (int);
        int i;
        int r;
        int src [20];
        int tgt [20];
    
        for (i = 0; i < 20; src [i] = i++);
    
        srand ( (unsigned int) time (0) );
    
        for (i = 20; i > 0; i --)
        {
            r = rand () % i;
            memcpy (&tgt [20 - i], &src [r], elesize);
            memcpy (&src [r], &src [i - 1], elesize);
        }
        for (i = 0; i < 20; printf ("%d ", tgt [i++] ) );
    }
    

提交回复
热议问题