I am trying to shuffle an array and add the shuffled-set every time into 2D array using a loop. the problem is that the resulted 2D array contains the same shuffled-set for all rows, while the output of each shuffled-set is different.
So; what do I miss here?
var b=[1,2,3,4,5,6,7,8,9];
var matrix=[];
for(var i=0; i <5; i ++){
shuffle(b);
matrix[i]=b;
//matrix.push(b);
console.log(b);
}
console.log(matrix);
function shuffle(array) {
var ctr = array.length, temp, index;
while (ctr > 0) {
index = Math.floor(Math.random() * ctr);
ctr--;
temp = array[ctr];
array[ctr] = array[index];
array[index] = temp;
}
return array;
}
the output:
Array(9) [ 7, 3, 4, 9, 2, 1, 6, 8, 5 ]
Array(9) [ 5, 6, 3, 9, 8, 4, 1, 7, 2 ]
Array(9) [ 9, 5, 2, 4, 3, 6, 8, 7, 1 ]
Array(9) [ 3, 5, 2, 1, 4, 9, 6, 8, 7 ]
Array(9) [ 5, 9, 4, 6, 7, 3, 2, 8, 1 ]
(5) […]
0: Array(9) [ 5, 9, 4, … ]
1: Array(9) [ 5, 9, 4, … ]
2: Array(9) [ 5, 9, 4, … ]
3: Array(9) [ 5, 9, 4, … ]
4: Array(9) [ 5, 9, 4, … ]
length: 5