I have a value that I need to divide it into non-equal parts with several numbers.
eg, if I get the number 100, it could generate 20,30,10,20, 5, 15 = 100
The problem is that my code is wrong, the program hangs, it does not leave the number 2.
function separate($val) {
if ($val == 1) {
return "1";
}
$list = [];
$total = 0;
while (true) {
$tmp = rand(1, $val);
if ($tmp + $total == $val) {
$list[] = $tmp;
$total += $tmp;
break;
} else {
$list[] = $tmp;
$total += $tmp;
}
}
return json_encode($list);
}
foreach (range(1, 500) as $m) { // gera ate 500 de prêmio
print "{$m}\n";
var_dump(separate($m));
print "=======\n";
}