数独生成--Javascript

       这是另一篇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>

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值