【发布时间】:2018-10-16 17:44:34
【问题描述】:
魔方:任何行、列或对角线长度的总和始终等于相同的数字。所有 9 个数字都是不同的正整数。
我在 JavaScript 中是这样做的,但是生成所有这些的最佳方式是什么?
function getMagicSquare() {
let myArray = [
[4, 9, 2],
[3, 5, 7],
[8, 1, 5]
];
for (let index1 = 1; index1 < 10; index1++) {
for (let index2 = 1; index2 < 10; index2++) {
for (let index3 = 1; index3 < 10; index3++) {
for (let index4 = 1; index4 < 10; index4++) {
for (let index5 = 1; index5 < 10; index5++) {
for (let index6 = 1; index6 < 10; index6++) {
for (let index7 = 1; index7 < 10; index7++) {
for (let index8 = 1; index8 < 10; index8++) {
for (let index9 = 1; index9 < 10; index9++)
// if numbers are not distinct for each loop, I can break the loop and make it a bit faster
{
const mySet = new Set();
mySet.add(index1).add(index2).add(index3).add(index4).add(index5).add(index6).add(index7).add(index8).add(index9)
if ((mySet.size === 9))
if (
(index1 + index2 + index3 === index4 + index5 + index6) &&
(index4 + index5 + index6 === index7 + index8 + index9) &&
(index7 + index8 + index9 === index1 + index4 + index7) &&
(index1 + index4 + index7 === index2 + index5 + index8) &&
(index2 + index5 + index8 === index3 + index6 + index9) &&
(index3 + index6 + index9 === index1 + index5 + index9) &&
(index1 + index5 + index9 === index3 + index5 + index7)
) {
myArray[0][0] = index1;
myArray[0][1] = index2;
myArray[0][2] = index3;
myArray[1][0] = index4;
myArray[1][1] = index5;
myArray[1][2] = index6;
myArray[2][0] = index7;
myArray[2][1] = index8;
myArray[2][2] = index9;
console.log(myArray);
}
}
}
}
}
}
}
}
}
}
}
第二个问题:如果我想生成 NxN 幻方怎么办?
【问题讨论】:
-
geeksforgeeks.org/magic-square 可能会有所帮助。
-
如果你想生成一个任意大小的数组,你需要将它转换为使用某种递归算法,它自身嵌套 N 次。
-
@nlex 感谢您的链接。看起来您提到的链接是在谈论生成 1 个幻方。我有兴趣生成所有幻方。
-
如果你唯一的限制是“所有 9 个数字都是不同的正整数”,难道没有无限数量的幻方可能吗?
-
请注意,对于 3x3 幻方,只有
9! = 362880的可能性,因此很容易全部尝试。对于 4x4,有16! = 21 trillion的可能性,因此很难全部尝试。 5x5 是不可能的。所以对于更大的方块,你需要一个更聪明的算法。