Advent of Code - Day 5

Another easy day for Advent of Code. The first challenge was to simply iterate over a string (take an input string, add 1 to it, and increase that number), make a hash, and check to see if the hash begins with 5 zeroes. If it does, you take the number after the 5 zeroes as a password character. You keep appending to a password until you have seven characters:


var crypto = require('crypto');


var input = 'ojvtpuvg';
generatePassword(input);

function generatePassword(s) {
    console.log('input = '+s);
    let password = '';

    let i = -1;
    while(password.length < 8) {
        i++;
        var hash = crypto.createHash('md5').update(s + i).digest('hex');
        if(hash.indexOf('00000') === 0) {
            let pchar = hash.substr(5,1);
            password += pchar;
            console.log('Generating password: '+password);
        }
    }

    console.log('Final password: '+password);
}

The only real difficult part was finding the Node Hash function and that was just one Google search. Looking over it now, having a generatePassword function seems a bit silly but I was assuming part would possibly need it. (It didn't.)

Speaking of part 2 - all it did was specify that the two characters after the five zeroes now represent a password position and password character. So the solution got a bit more complex.


var crypto = require('crypto');


let input = 'ojvtpuvg';
generatePassword(input);

function generatePassword(s) {
    console.log('input = '+s);
    let password = ['','','','','','','',''];

    let i = -1;
    while(!passwordDone(password)) {
        i++;
        var hash = crypto.createHash('md5').update(s + i).digest('hex');
        if(hash.indexOf('00000') === 0) {
            let pchar = hash.substr(6,1);
            let pos = hash.substr(5,1);
            if(pos >= 0 && pos <= 7 && password[pos] === '') {
                console.log(hash, pchar, pos);
                password[pos] = pchar;
                console.log('Generating password: '+password);
            }
        }
    }

    console.log('Final password: '+password.join(''));
}

function passwordDone(inp) {
    for(i=0;i<inp.length;i++) {
        if(inp[i] === '') return false;
    }
    return true;
}

As I said - pretty easy. But that's how Advent of Code works. It lulls you into a sense of confidence and then destroys that without mercy.

You can find my repo of solutions here: https://github.com/cfjedimaster/adventofcode

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.

Want to read more like this?