Help me fill a container?

Firstly, apologies if this is in the wrong forum.

Here is a problem someone might like to have a go at. It’s driving me potty:

$container = x; // Container is simply that; it ‘contains’ a value
$shortfall = y; // Shortfall is the amount by which Container is shy of ‘Full’

// So if Container = 75 and Shortfall = 25, a ‘Full’ Container would be 100.
// $container + $shortfall = one ‘Full’ Container


C = 432; S = 130; P = 175;

I need a function or the algorythm to ‘fill’ the Container using a selection of C, S and/or P to make up a value equal to, or more than (but optimally so) the Shortfall. If, for example the Shortfall is 250, then 2 * S is the best answer. The objective is to use the smallest number of constants feasible, whilst appreciating that the higher the value of the constant, the more costly it is within the application. C’s cost more than P’s which cost more than S’s.

I suspect it’ll need a recursive function and I’m still getting my head around those :slight_smile:

If I suss it before I get options from here, I’ll say so and close the topic, but many thanks in advance if someone can help…

Well, it’s not very elegant but here’s one solution. It introduces the probability of leaving the container not quite full - a ‘feature’ we can document as ‘tolerance’.

if($shortfall >= 432)
$shortfall -= 432;
$container += 432;
if($shortfall >= 175)
$shortfall -= 175;
$container += 175;
if($shortfall >= 130)
$shortfall -= 130;
$container += 130;
if($shortfall < 130) $shortfall = 0;
// Live with a slight deficit. And stop the while-loop

Not exactly as I wanted as it will default to 1 X 432 in preference to say, 3 X 130 and 1 X 175 but I’ve a deadline. Gives me a working solution to slot in for now :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service