File tree 2 files changed +18
-22
lines changed
2 files changed +18
-22
lines changed Original file line number Diff line number Diff line change 33
33
$ pt2 += $ a [$ i ] * $ occurs ;
34
34
}
35
35
36
- echo "Day 1: Historian Hysteria " , PHP_EOL ;
36
+ echo "--- Day 1: Historian Hysteria --- " , PHP_EOL ;
37
37
echo "Part 1: " , $ pt1 , PHP_EOL ;
38
- echo "Part 1 : " , $ pt2 , PHP_EOL ;
38
+ echo "Part 2 : " , $ pt2 , PHP_EOL ;
39
39
echo "Took " , microtime (true ) - $ time_start , " seconds " , PHP_EOL ;
40
40
echo PHP_EOL ;
Original file line number Diff line number Diff line change 1
1
<?php
2
2
$ time_start = microtime (true );
3
3
4
- function is_safe ($ numbers ): bool
4
+ function is_safe (array $ numbers ): bool
5
5
{
6
- $ diffs = [] ;
6
+ $ diff_prev = 0 ;
7
7
for ($ i = 1 ; $ i < count ($ numbers ); $ i ++) {
8
8
$ diff = $ numbers [$ i ] - $ numbers [$ i - 1 ];
9
9
@@ -12,18 +12,12 @@ function is_safe($numbers): bool
12
12
return false ;
13
13
}
14
14
15
- $ diffs [] = $ diff ;
16
- }
17
-
18
- // sign of each diff must be the same as all other elements
19
- for ($ i = 1 ; $ i < count ($ diffs ); $ i ++) {
20
- if ($ diffs [$ i ] > 0 && $ diffs [$ i -1 ] < 0 ) {
15
+ // sign of each diff must match preceding diff
16
+ if ($ i >= 2 && $ diff > 0 != $ diff_prev > 0 ) {
21
17
return false ;
22
18
}
23
19
24
- if ($ diffs [$ i ] < 0 && $ diffs [$ i -1 ] > 0 ) {
25
- return false ;
26
- }
20
+ $ diff_prev = $ diff ;
27
21
}
28
22
29
23
return true ;
@@ -38,15 +32,17 @@ function is_safe($numbers): bool
38
32
if (is_safe ($ numbers )) {
39
33
$ pt1 ++;
40
34
$ pt2 ++;
41
- } else {
42
- for ($ i = 0 ; $ i < count ($ numbers ); $ i ++) {
43
- $ copy = $ numbers ;
44
- unset($ copy [$ i ]);
45
- $ copy = array_values ($ copy );
46
- if (is_safe ($ copy )) {
47
- $ pt2 ++;
48
- break ;
49
- }
35
+ continue ;
36
+ }
37
+
38
+ // for part 2, brute-force remove each number and see if safe
39
+ for ($ i = 0 ; $ i < count ($ numbers ); $ i ++) {
40
+ $ copy = $ numbers ;
41
+ unset($ copy [$ i ]);
42
+ $ copy = array_values ($ copy );
43
+ if (is_safe ($ copy )) {
44
+ $ pt2 ++;
45
+ break ;
50
46
}
51
47
}
52
48
}
You can’t perform that action at this time.
0 commit comments