Completed
Push — master ( 2ef9a2...e0a631 )
by Pol
02:35
created

Permutations::getPermutations()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 11
cts 11
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 3
nop 1
crap 4
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