title: Efficient value selection from Array
body: <p>I have a array that contains some values like </p>
  
  <ul>
  <li>250</li>
  <li>500</li>
  <li>1000</li>
  <li>2000</li>
  </ul>
  
  <p>Example :</p>
  
  <p>I want to mix milk based on asked volume.
  Some one asks 2800 ml milk.</p>
  
  <p>To able to reach this volume I want 2000ml and 1000ml package from the array. This the most efficient one. You also could select 6 x 500ml package but it's more work. </p>
  
  <p>The logic is to use the least packages as possible with least possible spillage.</p>
  
  <p>I wrote the following code. It seems to work but need to test it bit more. Maybe it's not the most efficient code but it seems to work. Any code optimizations are welcome and also couldn't answer my own question because the question was closed.</p>
  
  <pre><code>List&lt;int&gt; packages = new List&lt;int&gt;() { 250,500,1000,2000 };
  
          //packages = new List&lt;int&gt;(packages.OrderByDescending(x =&gt; x));
  
          int wantedVolume = 2800;
          int leftover = wantedVolume;
  
          List&lt;int&gt; selectedpackages = new List&lt;int&gt;();
  
          while(true)
          {
              var nearest = packages.OrderBy(x =&gt; Math.Abs((long)x - leftover)).First();
  
              selectedpackages.Add(nearest);
              leftover = leftover - nearest;
  
              if (selectedpackages.Sum() &gt;= wantedVolume)
              {
                  break;
              }
          }
  
          Console.WriteLine("");
  
          foreach (int i in selectedpackages)
          {
              Console.WriteLine("You need a package of " + i + "ml");
          }
  </code></pre>
  
  <p>If the needed volume is 1750 ml the code will select 2000ml package from array. That would be less handling but it will spill 250ml. The efficient selection would be 1000ml + 500ml + 250ml</p>
  
  <p>With needed volume of 2300 it will select</p>
  
  <p>2000ml
  250ml
  250ml</p>
  
  <p>But efficient with handling would be </p>
  
  <p>2000ml
  500ml</p>
  
  <p>The spillage is the same.</p>