Repository navigation
Expand file tree
/
Copy pathday2.php
More file actions
78 lines (76 loc) · 2.19 KB
/
Copy pathday2.php
File metadata and controls
78 lines (76 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
$input = file_get_contents('inputs/day2.txt');
$input = preg_split('/\r?\n/', $input);
$inputArray = [];
foreach ($input as $line) {
$inputArray[] = preg_split('/\s+/', trim($line));
}
function checkChange($array) {
$increasing = true;
$decreasing = true;
for ( $i = 1; $i < count( $array ); $i ++ ) {
$diff = $array[ $i ] - $array[ $i - 1 ];
if ( abs( $diff ) < 1 || abs( $diff ) > 3 ) {
return false;
}
if ( $diff > 0 ) {
$decreasing = false;
} elseif ( $diff < 0 ) {
$increasing = false;
}
if (!( $increasing || $decreasing )) {
return false;
}
}
return true;
}
function checkChange2($array) {
global $part1Counter;
$increasing = true;
$decreasing = true;
for ( $i = 1; $i < count( $array ); $i ++ ) {
$diff = $array[ $i ] - $array[ $i - 1 ];
if ( abs( $diff ) < 1 || abs( $diff ) > 3 ) {
return tryRemoveOneIndex($array, $i);
}
if ( $diff > 0 ) {
$decreasing = false;
} elseif ( $diff < 0 ) {
$increasing = false;
}
if (!( $increasing || $decreasing )) {
return tryRemoveOneIndex($array, $i);
}
}
$part1Counter++;
return true;
}
function tryRemoveOneIndex($array, $index) {
global $part2Counter;
$levelsCopy = $array;
unset( $levelsCopy[ $index ] );
if ( checkChange( array_values( $levelsCopy ) ) ) {
$part2Counter++;
return true;
}
$levelsCopy = $array;
unset( $levelsCopy[ $index - 1 ] );
if ( checkChange( array_values( $levelsCopy ) ) ) {
$part2Counter++;
return true;
}
$levelsCopy = $array;
unset( $levelsCopy[ 0 ] );
if ( checkChange( array_values( $levelsCopy ) ) ) {
$part2Counter++;
return true;
}
return false;
}
$part1Counter = 0;
$part2Counter = 0;
foreach ($inputArray as $keyInput => $value) {
checkChange2($value);
}
echo "<p>The answer for part 1 is: $part1Counter";
echo "<p>The answer for part 2 is: ".$part1Counter+$part2Counter;