Created
June 2, 2019 08:32
-
-
Save fullpipe/cf2cd6f8f45968c253e6080319183fe2 to your computer and use it in GitHub Desktop.
Iterator over combinations of array elements.
This file contains hidden or 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 | |
class Combinator implements \Iterator | |
{ | |
/** | |
* @var array | |
*/ | |
private $data; | |
/** | |
* @var array | |
*/ | |
private $levels; | |
/** | |
* @var int | |
*/ | |
private $position; | |
/** | |
* Constructor. | |
* | |
* @param array $data | |
*/ | |
public function __construct(array $data) | |
{ | |
$this->data = $data; | |
$this->rewind(); | |
} | |
public function rewind() | |
{ | |
$this->levels = array_fill(0, count($this->data), 0); | |
$this->position = 0; | |
} | |
public function current() | |
{ | |
$data = $this->data; | |
$comb = []; | |
foreach ($this->levels as $level => $idx) { | |
$comb[] = array_splice($data, $idx, 1)[0]; | |
} | |
return $comb; | |
} | |
public function key() | |
{ | |
return $this->position; | |
} | |
public function valid() | |
{ | |
return 0 == $this->position || array_sum($this->levels) > 0; | |
} | |
public function next() | |
{ | |
++$this->position; | |
foreach ($this->levels as $level => $idx) { | |
++$idx; | |
if ($idx >= count($this->levels) - $level) { | |
$idx = 0; | |
} | |
$this->levels[$level] = $idx; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment