-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNonTerminal.php
More file actions
74 lines (62 loc) · 1.88 KB
/
Copy pathNonTerminal.php
File metadata and controls
74 lines (62 loc) · 1.88 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
<?php
declare(strict_types=1);
namespace Paths\GraphNode;
use Paths\PartialPath;
use Paths\Path;
use Paths\GraphNode;
class NonTerminal extends GraphNode
{
private array $children = [];
public function setChildren(array $children): void
{
$this->children = $children;
}
public function appendChild(GraphNode $child): void
{
$this->children[] = $child;
}
public function isTerminal(): bool
{
return false;
}
public function getChildren(): array
{
return $this->children;
}
/**
* @return \Generator<Path>
* Generate all paths to all terminals reachable from
* this node.
*/
public function allPathsToTerminals(PartialPath $prefix): \Generator
{
$previous_node = $prefix->lastNode();
$prefix = $prefix->withNonTerminal($this);
// Only follow "forward" paths by only going to children with
// greater indices than the previous node on the path.
//
// n.b.: This assumes that the indices of `$children` are
// monotonically incrementing by 1. If this ever isn't the case
// we'll need to call `array_values` on it.
$starting_index = array_search($previous_node, $this->children, $strict = true);
if ($starting_index === false) {
$starting_index = -1;
}
if ($starting_index + 1 <= count($this->children) - 1) {
foreach (range($starting_index + 1, count($this->children) - 1) as $i) {
yield from $this->children[$i]->allPathsToTerminals($prefix);
}
}
}
/**
*
* @return \Generator<Terminal>
* Generate all the terminal nodes reachable from this node
*/
public function allTerminals(): \Generator
{
foreach ($this->children as $child) {
yield from $child->allTerminals();
}
}
}