Skip to content

Instantly share code, notes, and snippets.

@Mykola-Veryha
Created May 22, 2019 02:17
Show Gist options
  • Save Mykola-Veryha/79badfbd2e4e9113b6f2a2cf4cd57c81 to your computer and use it in GitHub Desktop.
Save Mykola-Veryha/79badfbd2e4e9113b6f2a2cf4cd57c81 to your computer and use it in GitHub Desktop.
<?php
/*
* Mask before start
* 000000
* 111111
* 222222
*
* First row
* 001122
*
* Mask after first row
* 110000
* 222211
*
* Two rows
* 001122
* 120201
*
* Mask after second row
* 212010
*/
class Comb {
protected $elements_count;
protected $row_count;
protected $columns_count;
protected $mask;
public function call(int $elements_count) {
$this->elements_count = $elements_count;
$this->row_count = $elements_count;
$this->mask();
$result = [];
$x = 0;
$y = 0;
for ($row_index = 0; $row_index < $this->row_count; $row_index++) {
$repeat_count = $this->fact($this->row_count - $row_index - 1);
$mask_row = 0;
for ($group_index = 0; $group_index < ($this->columns_count / $repeat_count); $group_index++) {
if ($mask_row >= count($this->mask[$x])) {
$mask_row = $mask_row % count($this->mask[$x]);
}
$repeat_value = $this->mask[$x][$mask_row];
for ($repeat_index = 0; $repeat_index < $repeat_count; $repeat_index++) {
$result[$x][$y] = $repeat_value;
unset($this->mask[$x][$mask_row]);
$this->mask[$x] = array_values($this->mask[$x]);
$x++;
if ($x == $this->columns_count) {
$x = 0;
}
}
$mask_row++;
}
$y++;
}
return $result;
}
protected function mask() {
$this->columns_count = $this->fact($this->elements_count);
$mask = [];
for ($column_index = 0; $column_index < $this->columns_count; $column_index++) {
for ($row_index = 0; $row_index < $this->row_count; $row_index++) {
$mask[$column_index][$row_index] = $row_index;
}
}
$this->mask = $mask;
}
protected function fact(int $number) {
$factorial = 1;
for ($i = 1; $i <= $number; $i++){
$factorial = $factorial * $i;
}
return $factorial;
}
}
$c = new Comb();
$r = $c->call(4);
foreach ($r as $row){
foreach ($row as $value) {
echo $value . ' ';
}
echo "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment