我正在创建这个算法,该算法应该在方程式中包含数字
1,2,3,4,5
,如下所示:
@ + ## + ∗ ∗ ∗ + &&&& + $$$$$
这些符号意味着它可以是 5 个符号中的任何一个,但每个符号都指定其中的某个符号。然后比较方程的结果是否能被
11
整除,如果是则结束循环。
无法使用,请帮忙。
let cypherNum = [1, 2, 3, 4, 5]
function randomNum(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
for (let n = 0;
(n / 11 >= 0.0) && (Math.floor(n / 11) === n / 11) && n / 11 != Infinity; n++) {
function sequence() {
let selector1 = Math.round(randomNum(1, 5))
let number1 = cypherNum[selector1]
cypherNum -= [selector1]
let selector2 = Math.round(randomNum(1, 4))
let number2 = cypherNum[selector2]
cypherNum -= [selector2]
let selector3 = Math.round(randomNum(1, 3))
let number3 = cypherNum[Math.round(selector3)]
cypherNum -= [selector3]
let selector4 = Math.round(randomNum(1, 2))
let number4 = cypherNum[Math.round(randomNum(1, 2))]
cypherNum -= [selector4]
let number5 = cypherNum[1]
cypherNum -= [1]
let num = (number1) + (number2 * 11) + (number3 * 111) + (number4 * 1111) + (number5 * 11111)
}
console.log(sequence())
}
有几个问题:
-=
不会删除数组条目。您可以使用 splice
方法来实现这一点。num
是否是11的倍数,而是对n
执行不相关的测试。randomNum
已经返回一个整数,因此在其上调用 Math.round
是没有意义的。我建议在每次迭代中随机化 cypherNum
数组的
order(对其进行洗牌)。此外,可以使用
reduce
调用来计算总和,利用以下事实:对于 i
的某个值,这 1111 个系数等于 (10𝑖−1)/9。
看起来是这样的:
function randomNum(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = randomNum(0, i);
[array[i], array[j]] = [array[j], array[i]];
}
}
const cypherNum = [1, 2, 3, 4, 5];
const coeff = cypherNum.map((_, i) => (10 ** (i + 1) - 1) / 9); // 1, 11, 111, ....
console.log("coefficients are:", ...coeff);
let num = 1;
let i = 0;
for (i = 0; num % 11; i++) {
shuffle(cypherNum);
num = cypherNum.reduce((sum, digit, i) => sum + digit * coeff[i]);
}
console.log(`Found solution after ${i} iterations:`);
const s = cypherNum.map((digit, i) => digit * coeff[i]).join(" + ");
console.log(`${s} = ${num} and ${num} = 11 * ${num/11}`);