Created
August 17, 2015 22:04
-
-
Save Gerst20051/08c5bdc970a0ee219092 to your computer and use it in GitHub Desktop.
Permutation PHP Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$permutation = new Permutation(); | |
// $permutation = new Permutation(array_rand(range(0, 100), 4)); | |
class Permutation | |
{ | |
private $data = []; | |
private $permutations = []; | |
public function __construct($data = ['a', 'b', 'c', 'd']) | |
{ | |
$this->data = $data; | |
$this->calculatePermutations(); | |
$this->listPermutations(); | |
} | |
public static function permutations(array $elements) | |
{ | |
if (count($elements) <= 1) { | |
yield $elements; | |
} else { | |
foreach (self::permutations(array_slice($elements, 1)) as $permutation) { | |
foreach (range(0, count($elements) - 1) as $i) { | |
yield array_merge( | |
array_slice($permutation, 0, $i), | |
[$elements[0]], | |
array_slice($permutation, $i) | |
); | |
} | |
} | |
} | |
} | |
public function setData($data) | |
{ | |
$this->data = $data; | |
} | |
public function calculatePermutations() | |
{ | |
$this->permutations = []; | |
foreach (self::permutations($this->data) as $permutation) { | |
$this->permutations[] = $permutation; | |
} | |
} | |
public function listPermutations() | |
{ | |
var_dump($this->permutations); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment