entiendoNull - 1 year ago 62
PHP Question

# Finding out combinations of x amount of integers to sum a given number

I am trying to figure out how I can loop out possible combinations of a x amount of integers to sum a specifik number.

Let's say, I have number 7 and I need to figure out how I can sum that number with integers in pairs 3.
1+2+4 = 7

3+3+1 = 7

5+1+1 = 7

2+2+3 = 7

Repeated combinations of numbers doesn't interest me, e.g.:

1+2+4 = 7

2+4+1 = 7

4+2+1 = 7

Anyone got any ideas of how I should proceed to reach this result?
Thanks.

I've got a solution to my problem. I feel I should defientely share it here, if anyone would ever need it. My solutions is based on this post: https://stackoverflow.com/a/19067884/3293843

``````<?php
function sampling(\$chars, \$size, \$combinations = array()) {
# if it's the first iteration, the first set
# of combinations is the same as the set of characters
if (empty(\$combinations)) {
\$combinations = \$chars;
}

# we're done if we're at size 1
if (\$size == 1) {
return \$combinations;
}

# initialise array to put new values in
\$new_combinations = array();

# loop through existing combinations and character set to create strings
foreach (\$combinations as \$combination) {
foreach (\$chars as \$char) {
\$new_combinations[] = \$combination .'@'. \$char;
}
}

# call same function again for the next iteration
return sampling(\$chars, \$size - 1, \$new_combinations);

}

// example
\$chars = array('1', '2', '3','4');
\$target = 7;
\$maxLengthOfIntegers = 3;
\$output = sampling(\$chars, \$maxLengthOfIntegers);
\$repeatedEntries = array();

//presenting the output
foreach(\$output as \$out){
\$explodeOut = explode('@',\$out);
sort(\$explodeOut);
if(array_sum(\$explodeOut) == \$target){
\$sortedPattern = implode('',\$explodeOut);
if(!in_array(\$sortedPattern,\$repeatedEntries)){
echo \$sortedPattern.'<br/>';
\$repeatedEntries[] = \$sortedPattern;
}
}
}
?>
``````

Thank you for your time and efforts.

Regards, Jacob

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download