Home > Mobile >  Generate new random values and store in an array
Generate new random values and store in an array

Time:02-19

I am trying to generate two random values and store them in an array however I would like them to be different values each time a random number between 0-3 is generated.

function new_Randomvalues(n) {
    var array1 = [];
    for (var i = 0; i < n; i  ) {
        var row = Math.round(3*Math.random());
        var col = Math.round(3*Math.random());
        array1.push([row,col]);
    }
    return array1;
}
console.log(new_Randomvalues(10));

How do I edit this function where if an array of same numbers are pushed into array1 then remove those and generate 10 unique coordinates. Help would be appreciated thanks

CodePudding user response:

Per sam's question in the comments, here's the code:

function shuffle(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i   1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

pairs = [];

for (let i = 0; i <= 3; i  ) {
    for (let j = 0; j <= 3; j  ) {
        pairs.push([i, j]);
    }
}

shuffle(pairs);

pairs = pairs.slice(0, 10);

console.log(pairs);

  • Related