Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Getting random combinations to specified input

Tags:

php

I am trying to display possibilities for additions of specific numbers but have not been getting the right results.

<?php

$num3 = 20;
$set = null;
$balance = $num3;

    $dig = mt_rand(1,5);
    for($i = $balance; $i > 0; $i -= $dig ){
        echo $dig.'<br>';
        if($i < 1){
            $set .= $i;
            $balance = 0;
        }
        else{
            $set .= $dig.'+';
            $dig = mt_rand(1,5);
        }
    }
echo $set.'='.$num3;
?>

Here are some of the outputs:

2+5+1+4+5+3+=20
1+4+3+5+3+=20
3+1+1+2+3+4+4+1+3+=20

Appreciate any pointers. Thank in advance...

like image 724
Joe Shamuraq Avatar asked Nov 17 '25 09:11

Joe Shamuraq


1 Answers

Ok, even though the requirement isn't completely clear, here's an approach: (edit: demonstrating prevention of endless loop)

$max_loops = 1000; 
$balance = 20;
$found = [];
while($balance > 0 && $max_loops-- > 0) {
    $r = mt_rand(1, 5);
    if ($balance - $r >= 0) {
        $found[] = $r;
        $balance -= $r;
    }
}
echo implode(' + ', $found) . ' = '.array_sum($found);

Note: This code has a small risk of getting caught in an endless loop... though it's doubtful that it'll ever happen :)

Edit: Now the loop contains a hard-limit of 1000 iterations, after which the loop will end for sure...

To provoke an endless loop, set $balance = 7 and modify mt_rand(4, 5).

like image 183
Honk der Hase Avatar answered Nov 20 '25 00:11

Honk der Hase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!