-1

This is how I generate 6 different numbers:

window.random_row = Math.floor(Math.random() * (len_board - 1)) + 1;
window.random_column = Math.floor(Math.random() * (len_board - 1)) + 1;
window.random_row2 = Math.floor(Math.random() * ((len_board-1) - 1)) + 1;
window.random_column2 = Math.floor(Math.random() * ((len_board-1) - 1)) + 1;
window.random_row3 = Math.floor(Math.random() * ((len_board+1) - 1)) + 1;
window.random_column3 = Math.floor(Math.random() * ((len_board+1) - 1)) + 1;

However, I don't want the rows/columns to be the same number, e.g random_row == random_column is allowed, but I don't want random_row == random_row2. I was thinking of using an if/else statement. Something along the lines of: if (random_row == random_row2) then generate a new random_row2 but it came to my mind that the number could be the same again so I guess that would not be the right way to go about it. Does anyone have an idea about how to solve this issue?

A.S.J
  • 627
  • 3
  • 14
  • 38
  • Possible duplicate of [Generate unique random numbers between 1 and 100](https://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100) – izstas Oct 15 '17 at 19:32
  • Possible duplicate of [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – Etheryte Oct 15 '17 at 19:45

3 Answers3

1

I saw a good answer in https://stackoverflow.com/a/2380113/5108174

Adapting to your question:

function generate(qt, len_board) {
    var arr = [];
    while(arr.length < qt) {
        var randomnumber = Math.floor(Math.random() * (len_board - 1)) + 1;
        if(arr.indexOf(randomnumber) > -1) continue;
        arr.push(randomnumber);
    }
    return arr;
} 

var rows=generate(3,len_board);
var columns=generate(3,len_board);

window.random_row = rows[0];
window.random_column = columns[0];
window.random_row2 = rows[1];
window.random_column2 = columns[1];
window.random_row3 = rows[2];
window.random_column3 = columns[2];
0

Create an array of numbers from 1 .. len-board shuffle it (sort with Math.random() < 0.5 sort function) take the first 6.

Think of it as like shuffling a deck of cards, that you cannot pull the same card twice.

All "unique".

eavichay
  • 507
  • 2
  • 7
-1

What about trying with a while cycle?

while(random2 == random1 || random2 == random3) 
{
random2= math.....;
}