가방 무게의 합을 계산하여 컨테이너 수로 나눕니다. 그런 다음 빈 패키지 알고리즘을 사용하여 개별 컨테이너에 가방을 분배하십시오. 예 : 귀하의 배열에서 한 번에 하나의 가방을 가져다가 컨테이너의 무게 플러스 귀하의 가방의 무게가 최대 가능한 용기의 무게보다 적은 첫 번째 컨테이너에 넣어.
http://en.wikipedia.org/wiki/Bin_packing_problem
업데이트 : 루비로 작성 예. PHP에서 다시 작성하기가 어렵지 않아야합니다. 그것은 가방을 용기에 비교적 균등하게 분배합니다 (더 정확한 해결책이있을 수 있습니다).
# A list of bags with different weights
list_of_bags = [11, 41, 31, 15, 15, 66, 67, 34, 20, 42, 22, 25]
# total weight of all bags
weight_of_bags = list_of_bags.inject(0) {|sum, i| sum + i}
# how many containers do we have at our disposal?
number_of_containers = 4
# How much should one container weight?
weight_per_container = weight_of_bags/number_of_containers
# We make an array containing an empty array for each container
containers = Array.new(number_of_containers){ |i| [] }
# For each bag
list_of_bags.each do |bag|
# we try to find the first container
containers.each do |container|
# where the weight of the container plus the weigth of the bag is
# less than the maximum allowed (weight_per_container)
if container.inject(0) {|sum, i| sum + i} + bag < weight_per_container
# if the current container has space for it we add the bag
# and go to the next one
container.push(bag)
break
end
end
end
# output all containers with the number of items and total weight
containers.each_with_index do |container, index|
puts "container #{index} has #{container.length} items and weigths: #{container.inject(0) {|sum, i| sum + i}}"
end
예를 들어 결과 :
container 0 has 3 items and weigths: 83
container 1 has 3 items and weigths: 96
container 2 has 2 items and weigths: 87
container 3 has 2 items and weigths: 76
출처
2013-12-22 13:28:12
Max
귀하의 예는 불가능합니다. 각 용기는 110kg을 담아 야합니다. 가방 A를 30kg + 30kg e.i로 나눠야합니다. 그것을 가능하게합니다. 가능하지 않은 경우를 대비하여 false를 반환하는 함수를 원하십니까? 그리고 그렇지 않으면 컨테이너가있는 배열이 가능한데, 각 컨테이너는 가방을 가리키는 키가있는 배열입니까? – martti