Jump to content

split the number 100 into arrays of numbers that add up to 100


tallberg

Recommended Posts

tallberg: How practical would it be for you to use the recursive function above with a target of (for example) 10, then select 10 random entries from the returned array to give you a set of numbers that add up to 100.

 

That would give you numbers in the range 1-9, and a minimum of 20 values adding up to 100.

 

function recurse(&$final,&$working,$target) {
if (array_sum($working) > $target) {
	array_pop($working);
} elseif (array_sum($working) == $target) {
	$final[] = implode(',',$working);
} else {
	$tmpTarget = $target - array_sum($working);
	for ($i = 1; $i <= $tmpTarget; $i++) {
		$working[] = $i;
		recurse($final,$working,$target);
		array_pop($working);
	}
}
}

$final = $working = array();
recurse($final,$working,10);
shuffle($final);
$wrkArray = array_slice($final,0,9);
$wrkString = implode(',',$wrkArray);
echo $wrkString;

 

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.