eyedfox
eyedfox

Reputation: 714

How to use math.random again to get a different value if the values are the same in javascript

I am trying to get a different value from the previous value of math.random, so when the numbers are written to the document, if they are the same then math.random will generate another number that is not the same. It may need to keep generating until the value is different.

function rands() {
  return Math.floor(Math.random() * 20) + 1;
}

var rand1 = rands();
var rand2 = rands();
var rand3 = rands();
var rand4 = rands();
var rand = [];

function myFunction() {
  document.getElementById("random1").value = rand1;
  document.getElementById("random2").value = rand2;
  document.getElementById("random3").value = rand3;
  document.getElementById("random4").value = rand4;

  if(rand1 == rand2 || rand1==rand3 || rand1==rand4 || rand2 == rand3 || rand2 == rand4 || rand3==rand4){
  console.log("Duplicate");

    }
}

myFunction()

Upvotes: 0

Views: 969

Answers (2)

Mark
Mark

Reputation: 92440

If you want to guarantee uniqueness you can splice random indexes from an array. This will save the effort of repeatedly calling the function when you have clashes:

function rand_maker(length) {
    let arr = Array.from({length: length}, (_, i) => i+1)
    return () => {
        let index = Math.floor(Math.random() * arr.length)
        return arr.splice(index, 1)[0];
     }
}
let rands = rand_maker(20)
console.log(rands())
console.log(rands())
console.log(rands())
console.log(rands())

Once you can no longer make random numbers in the range, it will returned undefined.

Upvotes: 0

Nick
Nick

Reputation: 147146

You could rewrite your rands function to look for values which have already been used:

function rands(used) {
    let r;
    do {
        r = Math.floor(Math.random() * 20) + 1;
    } while (used.indexOf(r) >= 0);
    return r;
}

var rand = [];
for (let i = 0; i < 4; i++) rand[i] = rands(rand);

Upvotes: 4

Related Questions