SQRCAT
SQRCAT

Reputation: 5840

Determining the largest portions of values within an array to match a given value

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

Answers (3)

SQRCAT
SQRCAT

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

Mike X
Mike X

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

Dipen Shah
Dipen Shah

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

Related Questions