WaterL00
WaterL00

Reputation: 15

Trying to create a matrix with random numbers in JavaScript produces a matrix where all the rows are the same

When I try to create a matrix with random numbers, the matrix rows all appear the same. How do I fix this? The code for the problem is:

var sudokuRowMatrix = [];
var numbers = [];
var randomizedArray = [];
var sudokuColumnArray = [];
for(i=0;i<=8;i++){
    numbers[i]=i+1;
    sudokuRowMatrix[i] = [];
    sudokuColumnArray[i] = [];
}

function RandomizeArray(array){
    for(arrayIndex=0;arrayIndex<=8;arrayIndex++){
        randomArrayIndex = Math.floor(Math.random()*9);
        randomArrayIndex2 = Math.floor(Math.random()*9);
        placeHolder = array[randomArrayIndex];
        array[randomArrayIndex]=array[randomArrayIndex2];
        array[randomArrayIndex2] = placeHolder;
    }
    return array;
}

for(rowNumber=0;rowNumber<=8;rowNumber++){
    sudokuRowMatrix[rowNumber] = RandomizeArray(numbers);
}

All the rows of the matrix are the same

Upvotes: 1

Views: 51

Answers (1)

Marco Wagner
Marco Wagner

Reputation: 479

When you call RandomizeArray(numbers) you pass the numbers array as a reference. This means, that you always shuffle the same array and set it as a row in your Sudoku matrix and therefore shuffle all of your rows since they all hold the same reference.

An easy way to fix this, is to destructure your array before passing it to your method: sudokuRowMatrix[rowNumber] = RandomzieArray([...numbers]);

You can find my source here.

Upvotes: 2

Related Questions