Skip to content

Instantly share code, notes, and snippets.

@itsmee
Last active December 11, 2015 18:08
Show Gist options
  • Save itsmee/4639038 to your computer and use it in GitHub Desktop.
Save itsmee/4639038 to your computer and use it in GitHub Desktop.
A function in PHP that takes an integer and returns all sequences of numbers that sum to it. For example, 3 => (1, 1, 1), (1, 2), (2, 1), (3)
<?php
/**
* Returns an array containing all sequences of numbers that sum to $num,
* e.g. sequencesThatSumToNumber(3) => array(array(1, 1, 1), array(1, 2), array(2, 1), array(3))
*
* @param int $num
* @return array
*/
function sequencesThatSumToNumber($num) {
$result = array(); // base case
if ($num > 0) {
// take one summand and add it to all sequences of the rest
for ($i = 1; $i < $num; ++$i) {
$subsequences = sequencesThatSumToNumber($num - $i);
foreach ($subsequences as $sequence) {
$result[] = array_merge(array($i), $sequence);
}
}
// don't forget to add $num, since it sums to itself too
$result[] = array($num);
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment