如果任何数字已知,如何最大程度地减少遍历 4 位 PIN 的所有可能组合所需的时间?

How to minimize the time it takes to iterate through all possible combinations of a 4-digit PIN, if any of the digits are already known?

如果我要暴力破解 PIN,我可以使用以下代码遍历所有可能的 PIN:

for (PIN = 0000; PIN <= 9999; PIN++) {
  console.log(String(PIN).padStart(4, '0'));
}
但是如果我知道第二个数字是 3 而最后一个数字是 7,我就是在浪费时间迭代不可能的组合。

我可以检查循环内组合的有效性,如下所示:

for (PIN = 0000; PIN <= 9999; PIN++) {
  if (String(PIN)[1] != '3' || String(PIN)[3] != '7') {
    continue;
  }
  console.log(String(PIN).padStart(4, '0'));
}

但我想避免完全迭代不可能的组合。我怎样才能做到这一点?


我实际上并没有暴力破解 PIN。我正在尝试通过暴力破解 this 竞赛的幻方解决方案。但我想更多的人熟悉破解密码然后解决幻方。

对你不知道的数字使用嵌套循环,然后将它们与你知道的数字组合起来。

for (let first_digit = 0; first_digit <= 9000; first_digit += 1000) {
    for (let third_digit = 0; third_digit <= 90; third_digit += 10) {
        let PIN = first_digit + 300 + third_digit + 7;
        console.log(String(PIN).padStart(4, '0'));
    }
}

您可以分别遍历 2 个未知数字。

let timestamp = performance.now();

for(let digit1 = 0; digit1 < 10; digit1++) {
  for(let digit2 = 0; digit2 < 10; digit2++) {
    const digit = digit1 + "3" + digit2 + "7";
    
    //console.log(digit);
  }
}

console.log("first iteration took " + (performance.now() - timestamp) + "ms");

timestamp = performance.now();

for (PIN = 0000; PIN <= 9999; PIN++) {
  if (String(PIN)[1] != '3' || String(PIN)[3] != '7') {
    continue;
  }
  
  //console.log(String(PIN).padStart(4, '0'));
}

console.log("second iteration took " + (performance.now() - timestamp) + "ms");