title: Packing a small number of packages into a fixed number of bins
body: <p>I have a list of package sizes. There will be a maximum of around 5 different sizes and they may occur a few times (&lt;50).</p>
  
  <pre><code>packages = [5,5,5,5,5,5,10,11]
  </code></pre>
  
  <p>I need to pack them into a fixed number of bins, for example 3.</p>
  
  <pre><code>number_of_bins = 3
  </code></pre>
  
  <p>The bins may vary in size (sum of the sizes of the packed packages) between 0 and, say, 2 (that is, the difference of the sum of the sizes of the packages in the bins must be equal or nearly equal). So having bins with <code>[1,2]</code> (=3) and <code>[2]</code> (=2) (difference is 1) is fine, having them with <code>[10]</code> (=10) and <code>[5]</code> (=5) (difference is 5) is not. </p>
  
  <p>It is possible not to sort all packages into the bins, but I want the solution where a minimum number of packages remains unpacked. </p>
  
  <p>So the best solution in this case (I think) would be</p>
  
  <pre><code>bins = [11,5],[10,5],[5,5,5]
  remaining = [5]
  </code></pre>
  
  <p>There's probably a knapsack or bin-packing algorithm to do this, but I haven't found it. I'm fine with brute-forcing it, but I'm not sure what's an efficient way to do that. </p>
  
  <p>Is there any efficient way of doing this easily? Did I just miss the relevant search term to find it?</p>
  
  <hr>
  
  <p>Another example: </p>
  
  <pre><code>packages = [5,10,12]
  number_of_bins = 2
  </code></pre>
  
  <p>leads to</p>
  
  <pre><code>bins = [12],[10]
  remaining = [5]
  </code></pre>
  
  <p>because </p>
  
  <pre><code>bins = [12],[10,5]
  </code></pre>
  
  <p>has bin sizes of 12 and 15 which vary by more than 2.</p>
  
  <p>Analog:</p>
  
  <pre><code>packages = [2,10,12]
  number_of_bins = 3
  </code></pre>
  
  <p>leads to</p>
  
  <pre><code>bins = [2],[],[]
  remaining = [12,10]
  </code></pre>