1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace drupol\phpermutations\Generators; |
6
|
|
|
|
7
|
|
|
use drupol\phpermutations\Combinatorics; |
8
|
|
|
use drupol\phpermutations\GeneratorInterface; |
9
|
|
|
use Generator; |
10
|
|
|
|
11
|
|
|
use function count; |
12
|
|
|
|
13
|
|
|
class Permutations extends Combinatorics implements GeneratorInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* The combinations generator. |
17
|
|
|
* |
18
|
|
|
* @var \drupol\phpermutations\Generators\Combinations |
19
|
|
|
*/ |
20
|
|
|
protected $combinations; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Permutations constructor. |
24
|
|
|
* |
25
|
|
|
* @param array<int, mixed> $dataset |
26
|
|
|
* The dataset |
27
|
|
|
* @param int|null $length |
28
|
|
|
* The length |
29
|
|
|
*/ |
30
|
2 |
|
public function __construct(array $dataset = [], $length = null) |
31
|
|
|
{ |
32
|
2 |
|
parent::__construct($dataset, $length); |
33
|
2 |
|
$this->combinations = new Combinations($dataset, $this->getLength()); |
34
|
2 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* {@inheritdoc} |
38
|
|
|
*/ |
39
|
2 |
|
public function count(): int |
40
|
|
|
{ |
41
|
2 |
|
return $this->combinations->count() * $this->fact($this->getLength()); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* {@inheritdoc} |
46
|
|
|
*/ |
47
|
2 |
|
public function generator(): Generator |
48
|
|
|
{ |
49
|
2 |
|
foreach ($this->combinations->generator() as $combination) { |
50
|
2 |
|
foreach ($this->get($combination) as $current) { |
51
|
2 |
|
yield $current; |
52
|
|
|
} |
53
|
|
|
} |
54
|
2 |
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* {@inheritdoc} |
58
|
|
|
*/ |
59
|
2 |
|
public function toArray(): array |
60
|
|
|
{ |
61
|
2 |
|
$data = []; |
62
|
|
|
|
63
|
2 |
|
foreach ($this->generator() as $value) { |
64
|
2 |
|
$data[] = $value; |
65
|
|
|
} |
66
|
|
|
|
67
|
2 |
|
return $data; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* The permutations generator. |
72
|
|
|
* |
73
|
|
|
* @param array<int, mixed> $dataset |
74
|
|
|
* The dataset |
75
|
|
|
* |
76
|
|
|
* @return Generator<array> |
77
|
|
|
*/ |
78
|
2 |
|
protected function get(array $dataset): Generator |
79
|
|
|
{ |
80
|
2 |
|
foreach ($dataset as $key => $firstItem) { |
81
|
2 |
|
$remaining = $dataset; |
82
|
|
|
|
83
|
2 |
|
array_splice($remaining, $key, 1); |
84
|
|
|
|
85
|
2 |
|
if (0 === count($remaining)) { |
86
|
2 |
|
yield [$firstItem]; |
87
|
|
|
|
88
|
2 |
|
continue; |
89
|
|
|
} |
90
|
|
|
|
91
|
2 |
|
foreach ($this->get($remaining) as $permutation) { |
92
|
2 |
|
array_unshift($permutation, $firstItem); |
93
|
|
|
|
94
|
2 |
|
yield $permutation; |
95
|
|
|
} |
96
|
|
|
} |
97
|
2 |
|
} |
98
|
|
|
} |
99
|
|
|
|