Skip to content

Instantly share code, notes, and snippets.

@pachacamac
Last active December 10, 2016 08:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pachacamac/a2f5fec2ebb77fd2540b to your computer and use it in GitHub Desktop.
Save pachacamac/a2f5fec2ebb77fd2540b to your computer and use it in GitHub Desktop.
1d first fit decreasing bin packing algorithm (see https://en.wikipedia.org/wiki/Bin_packing_problem)
def decreasing_first_fit(elements, max_bin_size)
bins = [elements.first.class.new]
elements.sort_by{|e| e.size}.reverse.each do |e|
found_place = false
bins.each_with_index do |bin, i|
if bin.size + e.size <= max_bin_size
bins[i] += e
found_place = true
#puts "found place for #{e} in bin #{i}"
break
end
end
unless found_place
bins += [e]
#puts "creating new bin for #{e}"
end
end
bins
end
a = [Array.new(1,1), Array.new(6,6), Array.new(2,2), Array.new(4,4), Array.new(5,5), Array.new(3,3)]
p decreasing_first_fit(a, 7)
a = ['1', '666666', '22', '4444', '55555', '333']
p decreasing_first_fit(a, 7)
# => [[6, 6, 6, 6, 6, 6, 1], [5, 5, 5, 5, 5, 2, 2], [4, 4, 4, 4, 3, 3, 3]]
# => ["6666661", "5555522", "4444333"]
@Tippellh07
Copy link

How do I change the size of the bins and what I want to go into the bins?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment