-2

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))
16
  • Why do you need this for a shuffle function? Can you show us your function? Commented Mar 18, 2023 at 3:30
  • Check stackoverflow.com/questions/2450954/… Commented Mar 18, 2023 at 3:31
  • @vr. Thanks for your reply. I need this bcoz each song have their own "id" , when the playing song ended, a function will be called (song.id + 1). But when I have shuffle on, I want the "song.id" to goes randomly Commented Mar 18, 2023 at 3:34
  • hey @James, I want it to be in range between 2 numbers Commented Mar 18, 2023 at 3:36
  • Create an array stackoverflow.com/questions/3746725/… and shuffle it stackoverflow.com/questions/2450954/… and you just pop off the array Commented Mar 18, 2023 at 3:44

3 Answers 3

1

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));

Sign up to request clarification or add additional context in comments.

2 Comments

With pleasure @ChimmFX I added another snippet to make the function more reusable...
@ChimmFX "it keep getting dupes" mean that you want no duplicate song id in your playlist. If it's the case just edit your question like : "How to get a list of random numbers in range (from 0 to 51) without duplicates"
1

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());

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.