Created
December 25, 2012 20:52
-
-
Save obukhov/4375338 to your computer and use it in GitHub Desktop.
Выводит комбинации n по k. Использование: php -f Combination.php k n
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 | |
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