这是另一篇Python博客的Javascript版本 。使用Javascript写的生成数独的程序。连续循环生成10000个数独矩阵,需要不到7秒的时间,浏览器是Chrome。也就是说,连续生成的话,一个数独矩阵只需要0.7毫秒。当然,单独生成一个数独矩阵的话时间是不定的,可能不到1毫秒,可能会达到20毫秒。但是,足够快了不是吗?Python版本的数独生成算法可以看我的另一篇博客,地址是https://blog.csdn.net/LiebeULQQ/article/details/77511530。
另外,项目的Github地址是https://github.com/LiebeU/Sudoku。如果这个数独生成算法对你有用的话,欢迎star me。
<!DOCTYPE html>
<html>
<head>
<title>Sudoku</title>
<meta charset="utf-8">
</head>
<body>
<script>
class Sudoku {
constructor() {
this.digits = this.blankMatrix(9);
}
blankMatrix(size) {
let newMatrix = [];
for (let i = 0;i < size;i ++) {
newMatrix.push([]);
}
return newMatrix;
}
makeDigits() {
let colLists = this.blankMatrix(9);
let areaLists = this.blankMatrix(3);
let nine = this.randNine();
let i = 0,
j = 0,
areaIndex = 0,
count = 0,
error = false,
first = 0;
for (i = 0;i < 9;i ++) {
colLists[i].push(nine[i]);
}
areaLists[0] = nine.slice(0, 3);
areaLists[1] = nine.slice(3, 6);
areaLists[2] = nine.slice(6);
for (i = 0;i < 8;i ++) {
nine = this.randNine();
if (i % 3 == 2) {
areaLists = this.blankMatrix(3);
}
for (j = 0;j < 9;j ++) {
areaIndex = Math.floor(j / 3);
count = 0;
error = false;
while (colLists[j].includes(nine[0]) || areaLists[areaIndex].includes(nine[0])) {
if (++count >= nine.length) {
error = true;
break;
}
nine.push(nine.shift());
}
if (error) return false;
first = nine.shift();
colLists[j].push(first);
areaLists[areaIndex].push(first);
}
}
this.digits = colLists;
return true;
}
randNine() {
const nine = this.nine();
let index = 0;
for (let i = 0;i < 5;i ++) {
index = this.randIndex();
[nine[0], nine[index]] = [nine[index], nine[0]];
}
return nine;
}
nine() {
return [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
randIndex() {
return Math.floor(Math.random() * 9);
}
}
window.onload = function() {
window.sudoku = new Sudoku();
const start = Date.now();
while (! sudoku.makeDigits());
const end = Date.now();
console.log(end - start);
console.log(sudoku.digits);
}
</script>
</body>
</html>