Skip to content

Instantly share code, notes, and snippets.

@chris-taylor
Created April 29, 2012 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-taylor/2549649 to your computer and use it in GitHub Desktop.
Save chris-taylor/2549649 to your computer and use it in GitHub Desktop.
Quick and dirty implementation of first fit decreasing algo for bin packing
import random
import time
N = 200
binsize = 8000;
xs = [100 * random.randint(1,40) for i in range(N)]
print '\nObjects to be packed:\n'
print xs
xs.sort()
xs.reverse()
bins = []
print '\n***Packing***\n'
start_time = time.time()
for x in xs: # For every object
finished = False
for (i,b) in enumerate(bins): # Loop through existing bins
if b > x: # If the piece fits
bins[i] = b - x # Put it in the bin
finished = True # We're done with this object
continue # Skip the remaining bins
if not finished:
bins.append(binsize - x) # Add a new bin with the object in it
print 'Objects packed: %d' % len(xs)
print ' Bins used: %d' % len(bins)
print ' Space wasted: %.1f percent' % (100 * float(sum(bins)) / float(len(bins) * binsize))
print ' Time taken: %.2f seconds\n' % (time.time() - start_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment