Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculate which products together would deliver the requested power
    primarykey
    data
    text
    <p>Let's say I've got three products:</p> <p><strong>Product A</strong> Will deliver 5 power. Costs 50.</p> <p><strong>Product B</strong> Will deliver 9 power. Costs 80.</p> <p><strong>Product C</strong> Will deliver 15 power. Costs 140.</p> <p>I want to know what combination of products I could buy when I need 7 power. I could buy two of <strong>A</strong> but one of <strong>B</strong> is cheaper.</p> <p>When I'd need 65 power. I would need 4 times <strong>C</strong> and 1 time <strong>A</strong> (costs 680). But I could also go for seven <strong>B</strong> products and one <strong>A</strong> (costs 610).</p> <p>I am looking for a way to calculate the possible combinations of products for the given amount of power I need.</p> <p>The way I tried doing this doesn't give me what I want:</p> <pre><code>// $products are sorted DESC on their $power $power = 65 while( $power &gt; 0 ) { foreach( $products as $productPower ) { if( ( $productPower &gt; $power &amp;&amp; $power - $productPower &gt; 0 ) || $productPower == end( $products ) ) { // Add product to list $power -= $productPower; break; } } } </code></pre> <p>This sample code will only give me 4 times <strong>C</strong> and one time <strong>A</strong>. How should I go about it?</p> <p><strong>EDIT</strong> The number of products is variable. Also, the specific cost and power is variable. So there may be 10 products with cheeper and more expensive price tags.</p> <p><strong>EDIT 2</strong> As I said above, I want to calculate the possible <strong>combinations</strong> (plural). Some people seem to have missed that in my description.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload