1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Barryvanveen\CCA; |
4
|
|
|
|
5
|
|
|
use Barryvanveen\CCA\Exceptions\LoopNotFoundException; |
6
|
|
|
|
7
|
|
|
class Runner |
8
|
|
|
{ |
9
|
|
|
/** @var Config */ |
10
|
|
|
protected $config; |
11
|
|
|
|
12
|
|
|
/** @var CCA */ |
13
|
|
|
protected $cca; |
14
|
|
|
|
15
|
3 |
|
public function __construct(Config $config, CCA $cca) |
16
|
|
|
{ |
17
|
3 |
|
$this->config = $config; |
18
|
|
|
|
19
|
3 |
|
$this->cca = $cca; |
20
|
3 |
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Run the CCA and return the $numIterations-th state. |
24
|
|
|
* |
25
|
|
|
* @param int $numIterations |
26
|
|
|
* |
27
|
|
|
* @return State |
28
|
|
|
*/ |
29
|
3 |
|
public function getLastState(int $numIterations): State |
30
|
|
|
{ |
31
|
|
|
do { |
32
|
3 |
|
$state = $this->cca->getState(); |
33
|
|
|
|
34
|
3 |
|
$iteration = $this->cca->cycle(); |
35
|
3 |
|
} while ($iteration < $numIterations); |
36
|
|
|
|
37
|
3 |
|
return $state; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Run the CCA and return an array with first $numIterations states. |
42
|
|
|
* |
43
|
|
|
* @param int $numIterations |
44
|
|
|
* |
45
|
|
|
* @return State[] |
46
|
|
|
*/ |
47
|
3 |
|
public function getFirstStates(int $numIterations): array |
48
|
|
|
{ |
49
|
3 |
|
$states = []; |
50
|
|
|
|
51
|
|
|
do { |
52
|
3 |
|
$states[] = $this->cca->getState(); |
53
|
|
|
|
54
|
3 |
|
$iteration = $this->cca->cycle(); |
55
|
3 |
|
} while ($iteration < $numIterations); |
56
|
|
|
|
57
|
3 |
|
return $states; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Run the CCA and return the first looping states it encounters. If no loop is found within $maxIterations, |
62
|
|
|
* a LoopNotFoundException exception will be thrown. |
63
|
|
|
* |
64
|
|
|
* @param int $maxIterations |
65
|
|
|
* |
66
|
|
|
* @throws LoopNotFoundException |
67
|
|
|
* |
68
|
|
|
* @return State[] |
69
|
|
|
*/ |
70
|
6 |
|
public function getFirstLoop(int $maxIterations) |
71
|
|
|
{ |
72
|
6 |
|
$states = []; |
73
|
6 |
|
$hashes = []; |
74
|
|
|
|
75
|
|
|
do { |
76
|
6 |
|
$state = $this->cca->getState(); |
77
|
6 |
|
$hash = $state->toHash(); |
78
|
|
|
|
79
|
6 |
|
$cycleEnd = false; |
80
|
6 |
|
if ($cycleStart = array_search($hash, $hashes) !== false) { |
81
|
3 |
|
$cycleEnd = count($states)+1; |
82
|
|
|
} |
83
|
|
|
|
84
|
6 |
|
$states[] = $state; |
85
|
6 |
|
$hashes[] = $hash; |
86
|
|
|
|
87
|
6 |
|
if ($cycleEnd !== false) { |
88
|
3 |
|
$states = array_slice($states, $cycleStart, $cycleEnd); |
|
|
|
|
89
|
|
|
|
90
|
3 |
|
return $states; |
91
|
|
|
} |
92
|
|
|
|
93
|
6 |
|
$iteration = $this->cca->cycle(); |
94
|
6 |
|
} while ($iteration < $maxIterations); |
95
|
|
|
|
96
|
3 |
|
throw new LoopNotFoundException(); |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|