猜猜密码程序不起作用?

时间:2018-02-14 02:53:10

标签: javascript loops for-loop infinite-loop

这个程序是为了猜测一个随机生成的4位数密码,然后输出获取正确代码所需的猜测量,但没有任何反应......

我的方法是使用for循环来尝试数字0 - 9的四个数字的每个可能组合。这是在无限循环内,只有在猜测密码时才会中断。

我不知道我的程序有什么问题,没有打印,但程序没有无限循环。

function start() {
    var secretPasscode = generateRandomPasscode();

    var i = 0;
    while(true){
        i++;

        var guess = "";

        for(var firstDigit = 0; firstDigit <= 9; firstDigit++){
            guess += firstDigit;
            for(var secondDigit = 0; secondDigit <= 9; secondDigit++){
                guess += secondDigit;
                for(var thirdDigit = 0; thirdDigit <= 9; thirdDigit++){
                    guess += thirdDigit;
                    for(var fourthDigit = 0; fourthDigit <= 9; fourthDigit++){
                        guess += fourthDigit;
                    }
                }
            }
        }
        return guess;

        if(guess == secretPasscode){
            break;
        }
        println("It took " + i + " guesses to get the correct");
    }

}

这是生成随机密码的代码:

function generateRandomPasscode() {
    var randomPasscode = "";

    for(var i = 0; i < 4; i++) {
        var randomDigit = Randomizer.nextInt(0, 9);
        randomPasscode += randomDigit;
    }

    return randomPasscode;
}

1 个答案:

答案 0 :(得分:0)

更严格的实现会意识到你的猜测算法只是从0开始的密码的详尽枚举,所以你的猜测可以用一个整数而不是字符串更紧凑地表示,所以......

function start() {
    var secretPasscode = generateRandomPasscode();
    for (var guessInt = 0; guessInt < 1000; guessInt++) {
        let guess = pad(`${guessInt}`,4);
        if(guess === secretPasscode){
            println(`we just started counting, and found the passcode at ${guessInt} `);
            break;
        }
    }
}

function pad(str, length) {
    while (str.length < length) str = '0' + str;
    return str;
}