Assigning a range of integers randomly to an array


#1

Essentially I was attempting to assign a range of integers randomly to an array. I did this successfully using;

var x = Math.floor(Math.random()*4)+1;
var y = (Math.floor(Math.random()*4)+1);
var z = (Math.floor(Math.random()*4)+1);
var w = (Math.floor(Math.random()*4)+1);


while (x === y || x === z || x === w || y === z || y === w || z === w) {
    var y = (Math.floor(Math.random()*4)+1)
    var z = (Math.floor(Math.random()*4)+1);
    var w = (Math.floor(Math.random()*4)+1);
}

var newArray = [x, y, z, w];

console.log(newArray);

However, I can't help but feel there would be an easier/more comprehensive way to do this. This method is a simple fix for small numbers but is there something else I could do which may facilitate a broader range of integers?


#2

Use Math.random() function.Google it man.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.