-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19.php
120 lines (113 loc) · 2.81 KB
/
19.php
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
$contents = trim(file_get_contents('19-input.txt'), "\n");
$rows = explode("\n", $contents);
$grid = [];
foreach ($rows as $y => $row) {
$r = [];
$cols = str_split($row);
foreach ($cols as $x => $col) {
if ($y == 0 && $col == '|') {
$start = $x;
}
$r[] = $col;
}
$grid[] = $r;
}
function is_valid(&$grid, &$x, &$y)
{
return ($grid[$y][$x] == '|'
|| $grid[$y][$x] == '-'
|| $grid[$y][$x] == '+'
|| preg_match('#[A-Z]#', $grid[$y][$x])
);
}
function traverse(&$grid, &$letters, &$x, &$y, &$dir)
{
if ($grid[$y][$x] == '|') {
if ($dir == 'l') {
$x--;
} elseif ($dir == 'r') {
$x++;
} elseif ($dir == 'u') {
$y--;
} elseif ($dir == 'd') {
$y++;
} else {
var_dump('invalid1'); die();
}
} elseif ($grid[$y][$x] == '-') {
if ($dir == 'l') {
$x--;
} elseif ($dir == 'r') {
$x++;
} elseif ($dir == 'u') {
$y--;
} elseif ($dir == 'd') {
$y++;
} else {
var_dump('invalid2'); die();
}
} elseif ($grid[$y][$x] == '+') {
if ($dir != 'l' &&
($grid[$y][$x+1] == '|'
|| $grid[$y][$x+1] == '-'
|| preg_match('#[A-Z]#', $grid[$y][$x+1]))
) {
$dir = 'r';
$x++;
} elseif ($dir != 'r' &&
($grid[$y][$x-1] == '|'
|| $grid[$y][$x-1] == '-'
|| preg_match('#[A-Z]#', $grid[$y][$x-1]))
) {
$dir = 'l';
$x--;
} elseif ($dir != 'u' &&
($grid[$y+1][$x] == '|'
|| $grid[$y+1][$x] == '-'
|| preg_match('#[A-Z]#', $grid[$y+1][$x]))
) {
$dir = 'd';
$y++;
} elseif ($dir != 'd' &&
($grid[$y-1][$x] == '|'
|| $grid[$y-1][$x] == '-'
|| preg_match('#[A-Z]#', $grid[$y-1][$x]))
) {
$dir = 'u';
$y--;
} else {
var_dump('invalid3');die;
}
} elseif (preg_match("#[A-Z]#", $grid[$y][$x])) {
$letters .= $grid[$y][$x];
if ($dir == 'l') {
$x--;
} elseif ($dir == 'r') {
$x++;
} elseif ($dir == 'u') {
$y--;
} elseif ($dir == 'd') {
$y++;
} else {
var_dump('invalid4'); die();
}
} else {
var_dump('invalid5'); die();
}
if (!is_valid($grid, $x, $y)) {
return false;
}
return true;
}
$steps = 0;
$letters = "";
$x = $start;
$y = 0;
$dir = 'd';
do {
$steps++;
$valid = traverse($grid, $letters, $x, $y, $dir);
} while ($valid);
echo 'Part A: ' . $letters . PHP_EOL;
echo 'Part B: ' . $steps . PHP_EOL;