Reputation: 15
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);
}
Upvotes: 1
Views: 51
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]);
Upvotes: 2