2

I have created a random number generator and I want to avoid repeating the same values. Here is my code:

function function1() {
  var randomNumber = Math.floor(Math.random() * 30) + 1;
  var imgName = "pic (" + randomNumber + ").jpg";
  document.getElementById("imgid2").src="Pictures" + "/" + imgName;
}
veben
  • 19,637
  • 14
  • 60
  • 80

2 Answers2

0

If you don't want repeats, one approach is to generate array of all possible values and then take random value from array everytime (and remove it at the same time). That way values never repeat.

K.H.
  • 1,383
  • 13
  • 33
0

To prevent repetitions, generate a shuffled array of all possible values. randojs.com makes it easy to do this. For a shuffled array of all numbers 0-30, all you have to say is:

var sequence = randoSequence(30);

console.log(sequence);
<script src="https://randojs.com/1.0.0.js"></script>

So, to convert your code, all you'll have to do is:

var sequence = randoSequence(30);
function function1() {
    if(sequence.length == 0){//refill the array once we've completely iterated through all possible values
        sequence = randoSequence(30);
    }

    var randomNumber = sequence.pop();
    var imgName = "pic (" + randomNumber + ").jpg";
    document.getElementById("imgid2").src="Pictures" + "/" + imgName;
}

Note that this code also loops through the complete set of all possible values AGAIN once we've run out. Like I said, this code uses randojs.com, so if you want to use it, make sure you toss this in the head tag of your html document:

<script src="https://randojs.com/1.0.0.js"></script>

Here's a proof of concept if you just want to hit "run" and see it work:

var sequence = randoSequence(30);

function function1() {
  if (sequence.length == 0) { //refill the array once we've completely iterated through all possible values
    sequence = randoSequence(30);
    console.log("ALL POSSIBLE VALUES REFILLED.");
  }

  console.log(sequence.pop());
}

for (var i = 0; i < 35; i++) function1();
<script src="https://randojs.com/1.0.0.js"></script>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15