How do you randomly generate X amount of numbers, between the range of Y and Z in JavaScript?

前端 未结 3 1802
情歌与酒
情歌与酒 2021-01-22 17:08

For example I would like to generate 5 unique numbers between 1 & 10. The results should be 5 numbers from 1 to 10(for example 2 3 4 8 10).

3条回答
  •  清歌不尽
    2021-01-22 17:44

    1. Fill up an array with your range of values
    2. Shuffle the array
    3. Pick the first 5 elements

    If the range is very large, and the number of values you want is pretty small (like, 5 distinct values in the range 1 ... 1000000) then you can try generating random numbers in the range and throw away (unlikely) duplicates until you have 5. The problem with the "keep trying" approach is that there's a teeny tiny chance you could spend a lot of time with a string of random values that give you a lot of duplicates. For a big range of values, that's so unlikely that it's probably worth risking it unless the software is giving oxygen to trauma patients or something.

提交回复
热议问题