Last active
December 10, 2016 08:39
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do I change the size of the bins and what I want to go into the bins?