Reputation: 5840
I have an array with values:
$values = array(
2,
4,
7.5,
9
);
And i have a separate value:
$total = 12;
What's the correct mathematical approach to pick out values from $values
, with the greater values coming first and the lesser values coming last, until the value of $total
is reached or closely approached, but never exceeded?
I am aware that this is a basic mathematical problem, but i am pretty incapable of maths, and i have no idea how to accomplish this.
Upvotes: 0
Views: 63
Reputation: 5840
Ironically, i ended up with a fairly compact piece of code, which beautifully solves the problem - and proves that this is not the knapsack problem per sé.
$total = 7.9;
$values = array(2, 2.5, 5, 8);
$computed = 0;
rsort($values);
foreach($values as $val) {
if($val + $computed > $total)
continue;
$computed += $val;
}
That's it.
Upvotes: 0
Reputation: 129
$minimum = 5;$maximum = 8;
$numbers= array(2,4,
7.5,
9
);
$newArray = array_filter($numbers,function ($value) use($minimum ,$maximum ) {
return ($value >= $minimum && $value <= $maximum );
});
Upvotes: 1
Reputation: 1919
there a working solution for you.
<?php
$values = array(
2,
4,
1.5,
1,
3,
5
);
$total = 12;
rsort($values);
$newarray = array();
foreach($values as $key)
{
if(array_sum($newarray) == $total)
{
array_pop($newarray);
break;
}
else if(array_sum($newarray) > $total)
{
break;
}
else
{
$newarray[] = $key;
}
}
?>
Upvotes: 1