我有许多不同尺寸(宽度和高度)的“砖块”和一个固定尺寸的容器。我想从顶部向下移动尽可能紧凑地布置容器内的砖块。考虑到前面的步骤,我已经选择了网格在任何步骤中都应该是最佳的标准。到目前为止,我有以下(低效)代码不起作用:
def fits?(x, y, w, h)
!((x + w > W) || (y + h > H))
end
def overlaps?(existing, modified)
existing[:x] + existing[:w] > modified[:x] && existing[:y] + existing[:h] > modified[:y] && modified[:x] + modified[:w] > existing[:x] && modified[:y] + modified[:h] > modified[:y]
end
AXIS = :x
W = 800
H = 6400
sizes = [
{ w: 200 , h: 200 },
{ w: 200 , h: 200 },
{ w: 400 , h: 400 },
{ w: 200 , h: 200 },
{ w: 200 , h: 200 },
{ w: 400 , h: 400 },
{ w: 600 , h: 600 },
{ w: 200 , h: 200 },
{ w: 800 , h: 800 },
]
existing = []
sizes.each do |size|
size[:x] = 0
size[:y] = 0
existing.each do |existing|
if overlaps?(size, existing)
if fits?(x = existing[:x] + existing[:w], y = existing[:y], size[:w], size[:h])
size[:x] = x
size[:y] = y
redo
end
if fits?(x = existing[:x], y = existing[:y] + existing[:h], size[:w], size[:h])
size[:x] = x
size[:y] = y
redo
end
case AXIS
when :x then size[:x] = 0; size[:y] = existing[:y] + existing[:h]
when :y then size[:y] = 0; size[:x] = existing[:x] + existing[:w]
end
end
end
puts "#{size[:x]} , #{size[:y]} , #{size[:w]} , #{size[:h]}"
existing << size
end
有什么想法可以解决这个问题吗?看起来这将是贪心算法的一个主要例子,但我无法弄清楚它应该是什么。