To generate array of random numbers in a given range in “C”

后端 未结 5 981
心在旅途
心在旅途 2020-12-20 08:23

i want to generate an array of random numbers for example if the range is [0,10] then the desired output to be 2 3 5 6 4 7 8 9 0 1 ( non repeatitive )

the problem

5条回答
  •  感动是毒
    2020-12-20 09:09

    + Put all your numbers in the result array
    + from N down to 2
    + ---- shuffle N elements
    + return array

    Example

    fillarray(arr, 10);
    for (n = 10; n > 1; n++) shufflearray(arr, n);
    /* done */
    


    Edit --- thanks downvoter! I didn't even realize I was doing too much work up there

    • Put all your numbers in the result array
    • from N down to 2
    • ---- swap element N with a random element from 1 to N
    • return array

提交回复
热议问题