Skip to content

Instantly share code, notes, and snippets.

@obukhov
Created December 25, 2012 20:52
Show Gist options
  • Save obukhov/4375338 to your computer and use it in GitHub Desktop.
Save obukhov/4375338 to your computer and use it in GitHub Desktop.
Выводит комбинации n по k. Использование: php -f Combination.php k n
<?php
if ($argc < 3) {
throw new Exception('Wrong params count');
}
$k = intval($_SERVER['argv'][1]);
$n = intval($_SERVER['argv'][2]);
if ($n <= 0 || $k <= 0 || $n > $k) {
throw new Exception('Illegal params');
}
echo 'Сочетания: ', PHP_EOL, '------', PHP_EOL;
$cursor = 0;
$v = array(-1);
$i = 0;
while ($cursor >= 0) {
$v[$cursor]++;
// Если курсор не в последней позиции, двигаемся вправо заполняя начальными значениями
while ($cursor < $n - 1) {
$cursor++;
$v[$cursor] = $v[$cursor - 1] + 1;
}
//Если разряд достиг максимума - смещаем курсор влево, пока не встретим немаксимальный разряд
while ($cursor >= 0 && $v[$cursor] == $k - ($n - $cursor)) {
$cursor--;
}
echo implode('-', $v), PHP_EOL;
$i++;
}
echo '------', PHP_EOL, 'Всего: ', $i, PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment