Jump to content

Combination of numbers


ematr1x

Recommended Posts

Hey guys, I have been trying to figure this out for a bit and it's really been stumping me.

 

I am trying to find every combination of 6 numbers that = x.

 

All numbers must be between 1 and 49 so the smallest number would be 21 (1 + 2 + 3 + 4 + 5 + 6) and the largest 279 (44 + 45 + 46 + 47 + 48 + 49)

 

Example:

 

Every combination of numbers a + b + c + d + e + f that equals 150

 

I'm thinking I can do it with a dozen do while loops

 


						$one = 1;
						$two = 2;
						$three = 3;
						$four = 4;
						$five = 5;
						$six = 6;
						//$num = 1;

						do {
							$total = $one + $two + $three + $four + $five + $six;
							$set = 1;
							echo "<tr>";
								echo "<td>" . $one . "</td>";
								echo "<td>" . $two. "</td>";
								echo "<td>" . $three . "</td>";
								echo "<td>" . $four . "</td>";
								echo "<td>" . $five . "</td>";
								echo "<td>" . $six . "</td>";
								echo "<td>" . $total . "</td>";
								echo "<td>" . $set . "</td>";
							echo "</tr>";
							$six++;

							$num++;
						}while($six < 49);

						do {
							$total = $one + $two + $three + $four + $five + $six;
							$set = 2;
							echo "<tr>";
								echo "<td>" . $one . "</td>";
								echo "<td>" . $two. "</td>";
								echo "<td>" . $three . "</td>";
								echo "<td>" . $four . "</td>";
								echo "<td>" . $five . "</td>";
								echo "<td>" . $six . "</td>";
								echo "<td>" . $total . "</td>";
								echo "<td>" . $set . "</td>";
							echo "</tr>";
							$five++;

							$num++;
						}while($five < 48);

 

Etc, etc  but there has to be a simpler way.

 

Thanks for any kind of help. :D

 

Cheers!

Link to comment
https://forums.phpfreaks.com/topic/228889-combination-of-numbers/
Share on other sites

try

<?php
$test = range(1, 49);
$target = 123;

function my_comb($target, $num, $array){
    $out = array();
    if($num == 1) if(in_array($target, $array)) return array(array($target)); else return FALSE;
    $a = $num * ($num - 1) / 2;
    $b = min($target - $a, max($array));
    $c = min(max($array)-$num+1,max($target-(max($array)*2-$num+2)*($num-1)/2,1));
    if($b < $num) return FALSE;
    if($c>max($array)) return false;
    for($i = $c; $i<= $b;$i++){
        if($c = my_comb($target-$i, $num-1, range(1,$i-1))){
            foreach ($c as $d){
                array_push($d, $i);
                $out[] = $d;
            }
        }
    }
    return $out;
}
$a = my_comb($target, 6, $test);
//print_r($a);
echo count($a);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.