我想将此函数编写为“ guessPasscode”,但认为我的代码不起作用。 (其他功能是正确的)应该将0000〜9999中的每个数字都猜测为四位数的密码。
我运行了该函数,但它不会打印出任何内容,而且我也不认为该函数以我想要的方式工作。
var guess = "";
var guessCode ="";
function start() {
var secretPasscode = generateRandomPasscode();
guessPasscode(secretPasscode);
}
// Checks whether the given guess passcode is the correct passcode
function isCorrect(guessCode, correctCode) {
return guessCode == correctCode;
}
// Generates a random 4 digit passcode and returns it as a String
function generateRandomPasscode() {
var randomPasscode = "";
for(var i = 0; i < 4; i++) {
var randomDigit = Randomizer.nextInt(0, 9);
randomPasscode += randomDigit;
}
return randomPasscode;
}
function guessPasscode(secretPasscode){
for (var a = 0; a < 10; a++){
guess += a;
for (var b = 0; b < 10; b++){
guess += b;
for(var c = 0; c < 10; c++){
guess += c;
for (var d = 0; d < 10; d++){
guess += d;
if (isCorrect(guessCode, secretPasscode)){
println("Success!");
break;
}
guess = 0; //I am not sure about this line though
}
}
}
}
if (isCorrect(guessCode, secretPasscode)){
println("Success!");
}
}
我希望它打印“成功”并在找到正确的密码后停止循环。
答案 0 :(得分:0)
那些嵌套的循环实在太疯狂了,效率低得令人难以置信。如果您想从0到9999进行猜测,只需运行循环,然后将零填充到左侧即可。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
for (let i = 0; i < 9999; i++) {
let guess = String(i).padStart(4, '0')
guessAnswer(guess)
//whatever logic here to exit loop on correct guess
}