-3

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))
halfer
  • 19,824
  • 17
  • 99
  • 186
ChimmFX
  • 47
  • 1
  • 5
  • Why do you need this for a shuffle function? Can you show us your function? – kelsny Mar 18 '23 at 03:30
  • Check https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – James Mar 18 '23 at 03: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 – ChimmFX Mar 18 '23 at 03:34
  • hey @James, I want it to be in range between 2 numbers – ChimmFX Mar 18 '23 at 03:36
  • Create an array https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n and shuffle it https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array and you just pop off the array – epascarello Mar 18 '23 at 03:44
  • I've voted to mark as a duplicate based on the title, but now I wonder if it is not an exact dup - you want to keep track of prior random numbers so they are not suggested again. If that is the case please amend the title, it is a critical detail (cc @TylerH). – halfer Mar 18 '23 at 20:19
  • (I am happy to cast a reopen vote if that is necessary). – halfer Mar 18 '23 at 20:20
  • hi @halfer, thanks for replying. I think I found the right answer and ready for my code so this post could be closed now ^^. btw sorry about my stupid title and wrong grammar because I'm just 15 and I'm from Vietnam. – ChimmFX Mar 19 '23 at 06:36
  • It's pretty hard for me to "get on well" with ppl on stackoverflow because my questions always be edited and so many downvotes out there. – ChimmFX Mar 19 '23 at 06:37
  • We don't close questions if the question author is finished with them. The point of Stack Overflow (which is rarely understood by new members) is to produce a useful set of programming Q&A for the future. We keep questions here - they may be put on hold, but we rarely delete them. – halfer Mar 19 '23 at 09:13
  • I suspect the downvotes may have been for asking a duplicate question - it's essential to search first. The search function at Stack Overflow is actually very good - it works well. I am not sure the marked duplicate is correct, but [this looks like a duplicate](https://stackoverflow.com/questions/28181663/assign-random-number-to-element-in-javascript-but-avoid-duplicates) (i.e. it takes duplicates into account). There are probably other duplicates. Don't take the downvotes personally - people aren't being mean. – halfer Mar 19 '23 at 09:16
  • Edits can be regarded as good, as a well formatted question can receive less downvotes. Plus, it will make the question more readable to future people who want to learn from the question and its answers. – halfer Mar 19 '23 at 09:17
  • @halfer yes, I understood "it keep getting dupes" mean that he want no duplicate song id in his playlist. So in this case this is not a duplicate question ;) – tatactic Mar 19 '23 at 18:45
  • @tatactic: you may be right, the OP doesn't appear to have given me an answer to that. Assuming it is not a duplicate of the linked question, we could reopen it and close it as a duplicate of my suggested duplicate. I wonder if the effort is not worth the reward in that case - and the question would still end up on hold. – halfer Mar 20 '23 at 00:27
  • @halfer yes, I hope this question will be closed like other questions out there. I'm so sorry because I'm being stupid and my grammar sucks. – ChimmFX Mar 20 '23 at 03:07
  • @ChimmFX: don't beat yourself up about on-hold questions - it is not stupid to have them. I have a few in my posting history. They can still be useful for future readers, often as a sign-post to similar questions. Don't worry either about your English grammar - that will improve with practice. Have a good day! – halfer Mar 20 '23 at 09:48

3 Answers3

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());
James
  • 20,957
  • 5
  • 26
  • 41
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));
tatactic
  • 1,379
  • 1
  • 9
  • 18
  • With pleasure @ChimmFX I added another snippet to make the function more reusable... – tatactic Mar 18 '23 at 14:12
  • 1
    @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" – tatactic Mar 19 '23 at 19:00
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.

starball
  • 20,030
  • 7
  • 43
  • 238
Jagroop
  • 1,777
  • 1
  • 6
  • 20