Skip to content

Commit 98d86d2

Browse files
committed
Refactor for 2016 day 5. Better readability and much faster.
1 parent 6740f83 commit 98d86d2

File tree

1 file changed

+25
-24
lines changed

1 file changed

+25
-24
lines changed

src/AdventSolutions/Year2016/Day5/Solution2016Day5.php

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,47 +6,48 @@
66

77
class Solution2016Day5 extends AbstractSolution
88
{
9+
private const HASH_PREFIX = '00000';
10+
private const PASSWORD_LENGTH = 8;
11+
912
public function solvePart1($input, $debug = false): string
1013
{
1114
$string = trim($input[0]);
1215
$password = '';
1316

14-
for ($i = 0; $i < PHP_INT_MAX; $i++) {
15-
$hash = md5($string . $i);
17+
$this->generatePassword($string, function ($hash, &$password) {
18+
$password .= $hash[5];
19+
return strlen($password) === self::PASSWORD_LENGTH;
20+
}, $password);
1621

17-
if (str_starts_with($hash, '00000')) {
18-
$password .= $hash[5];
19-
20-
if (strlen($password) === 8) {
21-
break;
22-
}
23-
}
24-
}
25-
2622
return "The password is: <info>$password</info>";
2723
}
2824

2925
public function solvePart2($input, $debug = false): string
3026
{
3127
$string = trim($input[0]);
32-
$password = array_fill(0, 8, null);
28+
$password = array_fill(0, self::PASSWORD_LENGTH, null);
3329

34-
for ($i = 0; $i < PHP_INT_MAX; $i++) {
35-
$hash = md5($string . $i);
30+
$this->generatePassword($string, function ($hash, &$password) {
31+
$position = $hash[5];
32+
if (is_numeric($position) && $position < self::PASSWORD_LENGTH && $password[$position] === null) {
33+
$password[$position] = $hash[6];
34+
}
35+
return !in_array(null, $password, true);
36+
}, $password);
3637

37-
if (str_starts_with($hash, '00000')) {
38-
$position = $hash[5];
38+
return "The password is: <info>" . implode('', $password) . "</info>";
39+
}
3940

40-
if (is_numeric($position) && $position < 8 && $password[$position] === null) {
41-
$password[$position] = $hash[6];
41+
private function generatePassword(string $string, callable $callback, &$password): void
42+
{
43+
for ($i = 0; $i < PHP_INT_MAX; $i++) {
44+
$hash = md5($string . $i);
4245

43-
if (!in_array(null, $password)) {
44-
break;
45-
}
46+
if (str_starts_with($hash, self::HASH_PREFIX)) {
47+
if ($callback($hash, $password)) {
48+
break;
4649
}
4750
}
4851
}
49-
50-
return "The password is: <info>" . implode('', $password) . "</info>";
5152
}
52-
}
53+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy