skip to Main Content

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


  1. I am also bulid feature like this recently .

    const usedIndexEntries = []; // array for recording utilised indexes
    
    function getRandomIndex() {
      let randomIndex = Math.floor(Math.random() * 52);
      if(usedIndexEntries.length == 52){
        usedIndexEntries = [];
      }
      while (usedIndexEntries.includes(randomIndex)) { // check if the index has already used
        randomIndex = Math.floor(Math.random() * 52); // generate a new random index if it has
      }
      usedIndexEntries.push(randomIndex); // add the index to the array of used indexes
      return randomIndex;
    }
    

    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.

    Login or Signup to reply.
  2. Here’s an example using the array shuffling technique.

    // shuffle swiped from https://stackoverflow.com/a/2450976
    function shuffle(array) {
      let currentIndex = array.length,  randomIndex;
    
      // While there remain elements to shuffle.
      while (currentIndex != 0) {
    
        // Pick a remaining element.
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex--;
    
        // And swap it with the current element.
        [array[currentIndex], array[randomIndex]] = [
          array[randomIndex], array[currentIndex]];
      }
    
      return array;
    }
    
    // build an array containing 0-51
    const arr = [];
    for (let i = 0; i < 52; i++) arr.push(i);
    
    shuffle(arr);
    
    // use arr.shift() to get the next song id
    console.log("first song is " + arr.shift());
    console.log("second song is " + arr.shift());
    console.log("third song is " + arr.shift());
    Login or Signup to reply.
  3. Here is a manner to get a list of random numbers for a playlist (same code for an Array of 52 indexes):

        let originalArray=[0, 1, 2, 3, 4];
        let arrayLength = originalArray.length;
        let playlist;
        let rndVal;
        let removed;
        
        function generatePlaylist(){
            playlist = [];
                for( var i = 0; i<arrayLength; i++){
                    rndVal = Math.floor(Math.random() * originalArray.length);
                    removed = originalArray.splice(rndVal,1);
                    playlist.push(removed);
                    console.log("value = " + rndVal + " Array = " + originalArray + " removed = " + removed);
                }
            return playlist;
        }
        console.log ("playlist = " + generatePlaylist());

    Edit : More reusable :

        let originalArray=[0, 1, 2, 3, 4];
        let arrayLength;
        let playlist;
        let rndVal;
        let removed;
        
        function generatePlaylist(arrayNum){
            playlist = [];
            arrayLength = arrayNum.length;
                for( var i = 0; i<arrayLength; i++){
                    rndVal = Math.floor(Math.random() * arrayNum.length);
                    removed = arrayNum.splice(rndVal,1);
                    playlist.push(removed);
                    console.log("value = " + rndVal + " Array = " + arrayNum + " removed = " + removed);
                }
            return playlist;
        }
        
        console.log ("playlist = " + generatePlaylist(originalArray));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search