-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8.php
More file actions
112 lines (85 loc) · 2.82 KB
/
Copy path8.php
File metadata and controls
112 lines (85 loc) · 2.82 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
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
<?php
$input = file("inputs/8.txt");
$instructions = str_split(trim($input[0]));
$nodes = [];
for($lineIndex = 2; $lineIndex < count($input); $lineIndex++){
$line = $input[$lineIndex];
[$node, $childNodes] = explode(" = ", trim($line));
[$leftNode, $rightNode] = explode(", ", substr($childNodes, 1, -1));
// var_dump($node);
// var_dump($leftNode);
// var_dump($rightNode);
// return;
$nodes[$node] = [$leftNode, $rightNode];
}
// var_dump($nodes);
// return;
$currentNode = "AAA";
$instructionIndex = 0;
$instructionsLength = count($instructions);
// var_dump($currentNode);
// return;
while($currentNode != "ZZZ"){
$currentInstruction = $instructionIndex % $instructionsLength;
if($instructions[$currentInstruction] == "L"){
$currentNode = $nodes[$currentNode][0];
}else if($instructions[$currentInstruction] == "R"){
$currentNode = $nodes[$currentNode][1];
}else{
var_dump($instructions[$currentInstruction]);
}
// var_dump($currentNode);
$instructionIndex++;
}
var_dump($instructionIndex);
$currentNodes = array_values(array_filter(array_keys($nodes), "endsWithA"));
$currentNodesLength = count($currentNodes);
$visitedSteps = [];
$instructionIndex = 0;
$instructionsLength = count($instructions);
// var_dump($currentNodes);
// return;
foreach($currentNodes as $currentNode){
$instructionIndex = 0;
while(!endsWithZ($currentNode)){
$currentInstruction = $instructionIndex % $instructionsLength;
if($instructions[$currentInstruction] == "L"){
$currentNode = $nodes[$currentNode][0];
}else if($instructions[$currentInstruction] == "R"){
$currentNode = $nodes[$currentNode][1];
}else{
var_dump($instructions[$currentInstruction]);
}
// var_dump($currentNode);
$instructionIndex++;
}
$visitedSteps[] = $instructionIndex;
// var_dump($instructionIndex);
}
var_dump(lcm($visitedSteps));
function gcd($a, $b){
if ($b == 0)
return $a;
return gcd($b, $a % $b);
}
function lcm($arr){
$ans = $arr[0];
for ($i = 1; $i < count($arr); $i++)
$ans = ((($arr[$i] * $ans)) / (gcd($arr[$i], $ans)));
return $ans;
}
function allVisited($array){
foreach($array as $element){
if($element == 0){
return false;
}
}
return true;
}
function endsWithA($var){
return str_ends_with($var, "A");
}
function endsWithZ($var){
return str_ends_with($var, "Z");
}
?>