Is there any way to generate random number within a range? I’m making a shuffle function for my audio player using React. I got my song.id
works well. Once a random number is "used" I don’t want it again.
But I want to randomly generate a number start with 0 and end with 51 (it can generate 0 and 51). I tried these but I keep getting dupes:
Math.floor(Math.random() * 52))
3
Answers
I am also bulid feature like this recently .
Here I am generating Random Index .If it is already used then it will regenerate till a unique index is found and when it reach at max level then we will empty the array and this process start again.
Here’s an example using the array shuffling technique.
Here is a manner to get a list of random numbers for a playlist (same code for an Array of 52 indexes):
Edit : More reusable :