DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 4: Secure Container

Collapse
 
smh30 profile image
Stephanie Hope • Edited

PHP again! I solved it within the first half hour but was too embarrassed by my code to post it here, so spent most of my evening figuring out how to make it look less bad, oops. And I overwrote my Part 1 code, so this is just Part 2:

$lower = 359282;
$upper = 820401;
$count = 0;

for ($i = $lower; $i <= $upper; $i++) {
    if (test_ascending(strval($i))) {
        if (test_exact_dup(strval($i))) {
            $count++;
        }
    }

}
echo $count;

function test_exact_dup($password)
{
    for ($i = 0; $i < 5; $i++) {
        $num = $password[$i];
        $count = substr_count($password, $num);
        if ($count == 2){
            return true;
        }
    }
    return false;
}

function test_ascending($password)
{
    for ($i = 0; $i < 5; $i++) {
        if ($password[$i] > $password[$i + 1]) {
            return false;
        }

    }
    return true;
}

I did take some inspiration from other solutions to make this improved version :)

Collapse
 
jbristow profile image
Jon Bristow

These are fine instincts that will serve you well in future pull requests.

No shame in making sure all the corners are sharp and you replaced all the variables named x, fart, someKindaFunc, etc. (I must admit to editing my posted code after an elegant refactor reveals itself to me)