JS和HTML中的数独

时间:2018-08-16 15:12:47

标签: javascript html algorithm

我正在尝试在JS中随机填充一个二维数组,但我想让每一行和每一列中生成的数字都是唯一的。这是我的进度。这可以用于3x3网格,我的意思是随机生成的数字,但是我想要像真正的数独一样的9x9大小。谢谢。

//create table
function UpdateTable() {
	var arr = [];
	while(arr.length < 10){
		var randomnumber = Math.floor(Math.random()*10);
		if(arr.indexOf(randomnumber) > -1 ) continue;
		arr[arr.length] = randomnumber;
	}

	tmp1 = 'cell' + 1;
	tmp2 = 'cell' + 2;
	tmp3 = 'cell' + 3;
	tmp4 = 'cell' + 4;
	tmp5 = 'cell' + 5;
	tmp6 = 'cell' + 6;
	tmp7 = 'cell' + 7;
	tmp8 = 'cell' + 8;
	tmp9 = 'cell' + 9;

	var temp = [tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8, tmp9];

	for (var i = 0; i < 10; i++) {
		document.getElementById(temp[i]).innerHTML = arr[i];
	}	
} 


UpdateTable();
<center>
	<div id="container">
		<div id="header">
			 <h1>Welcome</h1> 
		</div>
		<div id="content">
			<table border="1" id="lotto">
				<tr class="tr1">
					<td class="normal" id="cell1">&nbsp;</td>
					<td class="normal" id="cell2">&nbsp;</td>
					<td class="normal" id="cell3">&nbsp;</td>
				</tr>
				<tr class="tr2">
					<td class="normal" id="cell4">&nbsp;</td>
					<td class="normal" id="cell5">&nbsp;</td>
					<td class="normal" id="cell6">&nbsp;</td>

				</tr>
				<tr class="tr3">
					<td class="normal" id="cell7">&nbsp;</td>
					<td class="normal" id="cell8">&nbsp;</td>
					<td class="normal" id="cell9">&nbsp;</td>
				</tr>
			</table>
		</div>
	</div>
	<input type="button" value="Re-generate Numbers" onclick="UpdateTable();" />
</center>

4 个答案:

答案 0 :(得分:2)

我会考虑另一种方法。

创建一个简单的Sudoku板,如下所示,基本上将第一行向右移动3个位置(每3行)。

1,2,3,4,5,6,7,8,9   --> base row 1
4,5,6,7,8,9,1,2,3   --> shift base row 1 by 3 to right
7,8,9,1,2,3,4,5,6   --> shift base row 1 by 6 to right
2,3,4,5,6,7,8,9,1   --> shit base row by 1 to right (base row 2)
5,6,7,8,9,1,2,3,4   --> shift base row 2 by 3 to right
8,9,1,2,3,4,5,6,7   --> shift base row 2 by 6 to right
3,4,5,6,7,8,9,1,2   --> shift base row 1 by 2 to right (base row 3)
6,7,8,9,1,2,3,4,5   --> shift base row 3 by 3 to right
9,1,2,3,4,5,6,7,8   --> shift base row 3 by 6 to right

调用上面的数独基本板。

您现在可以随机排列列和行,并且仍然具有Sudoku董事会的合法组成。但是您需要小心。让我们将第1-3行,第4-6行,第2行和最后3行称为行3。列也是如此。我们可以将行块与其他行块交换,也可以将列块与其他列块交换,并且仍然具有Sudoku不变集。

您可以交换同一块内的列。

您可以在同一块中交换行。

您可以交换列索引为3列倍数的列。 (例如第1列和第4列,第1列和第7列,第3列和第9列...等等)

答案 1 :(得分:0)

请检查以下代码:

 
// we start with an empty sudoku...
var sudoku = new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
 
// ... and we solve it!!
solve(sudoku);
 
// given a sudoku cell, returns the row
function returnRow(cell) {
	return Math.floor(cell / 9);
}
 
// given a sudoku cell, returns the column
function returnCol(cell) {
	return cell % 9;
}
 
// given a sudoku cell, returns the 3x3 block
function returnBlock(cell) {
	return Math.floor(returnRow(cell) / 3) * 3 + Math.floor(returnCol(cell) / 3);
}
 
// given a number, a row and a sudoku, returns true if the number can be placed in the row
function isPossibleRow(number,row,sudoku) {
	for (var i=0; i<=8; i++) {
		if (sudoku[row*9+i] == number) {
			return false;
		}
	}
	return true;
}
 
// given a number, a column and a sudoku, returns true if the number can be placed in the column
function isPossibleCol(number,col,sudoku) {
	for (var i=0; i<=8; i++) {
		if (sudoku[col+9*i] == number) {
			return false;
		}
	}
	return true;
}
 
// given a number, a 3x3 block and a sudoku, returns true if the number can be placed in the block
function isPossibleBlock(number,block,sudoku) {
	for (var i=0; i<=8; i++) {
		if (sudoku[Math.floor(block/3)*27+i%3+9*Math.floor(i/3)+3*(block%3)] == number) {
			return false;
		}
	}
	return true;
}
 
// given a cell, a number and a sudoku, returns true if the number can be placed in the cell
function isPossibleNumber(cell,number,sudoku) {
	var row = returnRow(cell);
	var col = returnCol(cell);
	var block = returnBlock(cell);
	return isPossibleRow(number,row,sudoku) && isPossibleCol(number,col,sudoku) && isPossibleBlock(number,block,sudoku);
}
 
// given a row and a sudoku, returns true if it's a legal row
function isCorrectRow(row,sudoku) {
	var rightSequence = new Array(1,2,3,4,5,6,7,8,9);
	var rowTemp= new Array();
	for (var i=0; i<=8; i++) {
		rowTemp[i] = sudoku[row*9+i];
	}
	rowTemp.sort();
	return rowTemp.join() == rightSequence.join();
}
 
// given a column and a sudoku, returns true if it's a legal column
function isCorrectCol(col,sudoku) {
	var rightSequence = new Array(1,2,3,4,5,6,7,8,9);
	var colTemp= new Array();
	for (var i=0; i<=8; i++) {
		colTemp[i] = sudoku[col+i*9];
	}
	colTemp.sort();
	return colTemp.join() == rightSequence.join();
}
 
// given a 3x3 block and a sudoku, returns true if it's a legal block 
function isCorrectBlock(block,sudoku) {
	var rightSequence = new Array(1,2,3,4,5,6,7,8,9);
	var blockTemp= new Array();
	for (var i=0; i<=8; i++) {
		blockTemp[i] = sudoku[Math.floor(block/3)*27+i%3+9*Math.floor(i/3)+3*(block%3)];
	}
	blockTemp.sort();
	return blockTemp.join() == rightSequence.join();
}
 
// given a sudoku, returns true if the sudoku is solved
function isSolvedSudoku(sudoku) {
	for (var i=0; i<=8; i++) {
		if (!isCorrectBlock(i,sudoku) || !isCorrectRow(i,sudoku) || !isCorrectCol(i,sudoku)) {
			return false;
		}
	}
	return true;
}
 
// given a cell and a sudoku, returns an array with all possible values we can write in the cell
function determinePossibleValues(cell,sudoku) {
	var possible = new Array();
	for (var i=1; i<=9; i++) {
		if (isPossibleNumber(cell,i,sudoku)) {
			possible.unshift(i);
		}
	}
	return possible;
}
 
// given an array of possible values assignable to a cell, returns a random value picked from the array
function determineRandomPossibleValue(possible,cell) {
	var randomPicked = Math.floor(Math.random() * possible[cell].length);
	return possible[cell][randomPicked];
}
 
// given a sudoku, returns a two dimension array with all possible values 
function scanSudokuForUnique(sudoku) {
	var possible = new Array();
	for (var i=0; i<=80; i++) {
		if (sudoku[i] == 0) {
			possible[i] = new Array();
			possible[i] = determinePossibleValues(i,sudoku);
			if (possible[i].length==0) {
				return false;
			}
		}
	}
	return possible;
}
 
// given an array and a number, removes the number from the array
function removeAttempt(attemptArray,number) {
	var newArray = new Array();
	for (var i=0; i<attemptArray.length; i++) {
		if (attemptArray[i] != number) {
			newArray.unshift(attemptArray[i]);
		}
	}
	return newArray;
}
 
// given a two dimension array of possible values, returns the index of a cell where there are the less possible numbers to choose from
function nextRandom(possible) {
	var max = 9;
	var minChoices = 0;
	for (var i=0; i<=80; i++) {
		if (possible[i]!=undefined) {
			if ((possible[i].length<=max) && (possible[i].length>0)) {
				max = possible[i].length;
				minChoices = i;
			}
		}
	}
	return minChoices;
}
 
// given a sudoku, solves it
function solve(sudoku) {
	var saved = new Array();
	var savedSudoku = new Array();
	var i=0;
	var nextMove;
	var whatToTry;
	var attempt;
	while (!isSolvedSudoku(sudoku)) {
		i++;
		nextMove = scanSudokuForUnique(sudoku);
		if (nextMove == false) {
			nextMove = saved.pop();
			sudoku = savedSudoku.pop();
		}
		whatToTry = nextRandom(nextMove);
		attempt = determineRandomPossibleValue(nextMove,whatToTry);
		if (nextMove[whatToTry].length>1) {
			nextMove[whatToTry] = removeAttempt(nextMove[whatToTry],attempt);
			saved.push(nextMove.slice());
			savedSudoku.push(sudoku.slice());
		}
		sudoku[whatToTry] = attempt;
	}
	showSudoku(sudoku,i);
}
 
function showSudoku(sudoku,i) {
	var sudokuText = "<table border='1'>";
	for (var i=0; i<=8; i++) {
		sudokuText+="<tr>";
		for (var j=0; j<=8; j++) {
			sudokuText+="<td>";
			sudokuText+=sudoku[i*9+j];
			sudokuText+="</td>";
		}
		sudokuText+="</tr>";
	}
	sudokuText+="</table>";
	document.write(sudokuText);
}
table {
    display:table;
    border: 2px solid #444;
    border-collapse: collapse;
    position: relative;
}
table tr {
    display:table-row;
    position: relative;
    z-index:-1;
}
table td{
    display:table-cell;
    padding:8px;
    border: 1px solid #ff0000;
    text-align: center;
}

table td:nth-child(3), table td:nth-child(6){border-right: 5px solid #555; } /*vertical*/
table tr:nth-child(3) td, table tr:nth-child(6) td{border-bottom: 5px solid #555;}  /*horizontal*/

我希望对您有所帮助。 谢谢

答案 2 :(得分:0)

首先创建一个由81个Position对象组成的数组。

function Pos() {
}

const board = [];
for (let i = 0; i < 81; i++) {
  board.push(new Pos())
}

遍历数组(可能几次)并创建3个数组数组; 垂直线 水平线 和9个部分

const xLines = [[], ...],
      yLines = [[], ...],
      sLines = [[], ...];

这些数组中的每一个当然应该有9个数组。 使用对board变量中的Position对象的引用填充它们。

让板变量中的每个位置都引用其水平/垂直线和截面数组。

//81 objects
//board = [{x, y, s, xArr, yArr, sectionArr}, ..]

现在,您将能够生成数字,知道已经使用了哪些数字。

专业提示: 一次生成一条水平线(到达第3条时,每个部分只有3位数字)

答案 3 :(得分:-1)

方法是

  1. 创建一个代表空9x9数组的变量。使用[[0,0,0,0,0,0,0,0,0,],...等零]
  2. 编写一个函数,当您调用时,该函数将获取给定坐标在同一行中的所有数字。 same_row(x_coord,y_coord),返回一个列表
  3. 编写相同的函数以获取同一列中的所有数字
  4. 循环遍历您的空数组,从[1、2、3、4、5、6、7、8、9]中随机选择一个不在同一行或同一列中的数字,然后填充该号码的位置

一个将返回与正方形相同的行中数字列表的函数可能类似于:

function (row_number, grid) {
  var nums = []
  for (var i = 0; i < 9; i++) {
    nums.push(grid[row_number][i])
  }
  return nums;
 }

一旦您自己编写了代码,请在代码高尔夫中再次提交此问题,并使用答案来改进自己的代码:)

相关问题