Home Guess the Passcode program not working?
Reply: 1

Guess the Passcode program not working?

High School Student
1#
High School Student Published in 2018-02-14 02:53:10Z

This program is meant to guess a randomly generated 4-digit passcode and then output the how many guesses it took to get the correct code, but nothing happens...

My approach was to use a for loop to try every single possible combination of four digits of the numbers 0 - 9. This is inside an infinite loop that will only break when the passcode is guessed.

I don't know what's wrong with my program, nothing is printed but the program doesn't loop infinitely.

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");
    }

}

This is the code that generates the random passcode:

function generateRandomPasscode() {
    var randomPasscode = "";

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

    return randomPasscode;
}
danh
2#
danh Reply to 2018-02-14 03:06:11Z

A tighter implementation would realize that your guessing algorithm is just the exhaustive enumeration of passcodes from 0, so your guess can more compactly represented by an integer, rather than a string, so...

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;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.318505 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO