我正在尝试在JavaScript的4 x 4网格上制作数独生成器。因此,我声明了一个对象矩阵,例如{number:0,cbd:1},它们表示将要在单元格上显示的数字,以及一个状态变量,用于控制该单元格以后是否可以被挖掘(cbd):] >
var matrix = new Array(4).fill({number: 0, cbd: 1}).map(() => new Array(4).fill({number: 0, cbd: 1}));
然后,我使用此功能填充网格,同时遵守了数独的所有3个限制:行,列和正方形均无重复:
fillmatrix4(matrix,tam){ var numberList = [...Array(4+1).keys()].slice(1); //[1,2,3,4] for(var k = 0; k < 4**2; k++){ var row = Math.floor(k/4); var col = k%4; if (matrix[row][col].number == 0){ numberList.sort(() => Math.random() - 0.5); //shuffles the array for(var q = 0; q < numberList.length; q++){ var ids = matrix[row].map(a => a.number); //creates an array with the number property from all cells in that row if (!(ids.includes(numberList[q]))){ //check if number is in row if ((matrix[0][col].number != numberList[q]) && (matrix[1][col].number != numberList[q]) && (matrix[2][col].number != numberList[q]) && (matrix[3][col].number != numberList[q])){ //check if number is in column var square = []; if (row<2){It is used to find out what subgrid we are in if (col<2){ square = [matrix[0][0].number, matrix[0][1].number, matrix[1][0].number, matrix[1][1].number]; } else { square = [matrix[0][2].number, matrix[0][3].number, matrix[1][2].number, matrix[1][3].number]; } } else { if (col<2){ square = [matrix[2][0].number, matrix[2][1].number, matrix[3][0].number, matrix[3][1].number]; } else { square = [matrix[2][2].number, matrix[2][3].number, matrix[3][2].number, matrix[3][3].number]; } } if (!(square.includes(numberList[q]))){ //check if number is that subgrid matrix[row][col].number = numberList[q]; //if number not in row, column and square, adds it to matrix if (this.checkGrid(matrix,tam)){ //returns true all matrix is filled return matrix; } } } } } } }
我知道此功能有效。我在整数矩阵上对其进行了测试,但我需要每个单独的单元格都具有该变量cbd。
但是现在,有了上面声明的对象矩阵,它不是“改组”。结果始终是这样填充网格:
a | a | a | a b | b | b | b c | c | c | c d | d | d | d where a,b,c,d are numbers from 1 to 4.
这可能是什么原因?
我正在尝试在JavaScript的4 x 4网格上制作数独生成器。因此,我声明了一个对象矩阵,例如{number:0,cbd:1},它们表示将要在单元格上显示的数字,以及...
[执行时: