6
6
7
7
class Solution2016Day5 extends AbstractSolution
8
8
{
9
+ private const HASH_PREFIX = '00000 ' ;
10
+ private const PASSWORD_LENGTH = 8 ;
11
+
9
12
public function solvePart1 ($ input , $ debug = false ): string
10
13
{
11
14
$ string = trim ($ input [0 ]);
12
15
$ password = '' ;
13
16
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 );
16
21
17
- if (str_starts_with ($ hash , '00000 ' )) {
18
- $ password .= $ hash [5 ];
19
-
20
- if (strlen ($ password ) === 8 ) {
21
- break ;
22
- }
23
- }
24
- }
25
-
26
22
return "The password is: <info> $ password</info> " ;
27
23
}
28
24
29
25
public function solvePart2 ($ input , $ debug = false ): string
30
26
{
31
27
$ string = trim ($ input [0 ]);
32
- $ password = array_fill (0 , 8 , null );
28
+ $ password = array_fill (0 , self :: PASSWORD_LENGTH , null );
33
29
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 );
36
37
37
- if ( str_starts_with ( $ hash , ' 00000 ' )) {
38
- $ position = $ hash [ 5 ];
38
+ return " The password is: <info> " . implode ( '' , $ password ) . " </info> " ;
39
+ }
39
40
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 );
42
45
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 ;
46
49
}
47
50
}
48
51
}
49
-
50
- return "The password is: <info> " . implode ('' , $ password ) . "</info> " ;
51
52
}
52
- }
53
+ }
0 commit comments