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