很显然,必须使用一只arrow子来排出最高的气球,而该箭不会击中左边的任何气球。 (如果最高高度有一个以上的气球,所有气球都必须按左对右的顺序单独穿透。) 这还可能把一些气球带走到最高气球的右边。 现在,在剩余的气球中,一个排位最高。 出于同样的理由,必须使用一只arrow子去除该气球,直至所有气球被击落。
因此,我们可以击落最大的气球,把该气球和所有气球的高度降为零,以防箭击中其世系。 直到所有气球都处于零高位之前,才再次出现这种情况。
下面是鲁比实施的法典。 在作解释后,我将作此规定,可视为假装,我预计可以轻易改装成“灰色”。
def pop_em_all(balloon_heights)
heights = balloon_heights.dup
shots = []
loop do
highest_left = highest_balloon_left(heights)
break if heights[highest_left] == 0
shots << highest_left
pop_with_shot(heights, highest_left)
end
shots
end
def highest_balloon_left(heights)
heights.each_index.max_by { |i| heights[i] }
end
def pop_with_shot(heights, highest_left)
current_height = heights[highest_left]
(highest_left..(heights.size - 1)).each do |balloon|
if heights[balloon] == current_height
heights[balloon] = 0
current_height -= 1
end
end
end
让我们尝试。
pop_em_all [5, 4, 3, 2, 1]
#=> [0]
pop_em_all [2, 1, 5, 4, 3]
#=> [2, 0]
pop_em_all [2, 1, 5, 5, 4]
#=> [2, 3, 0]
pop_em_all [2, 1, 5, 4, 3, 6, 1, 7, 3]
#=> [7, 5, 2, 8, 0, 6]
主要方法,pop_em_all
, 最初产生一份balloon_h 8,/code>, 称为hels
。 这样做是为了避免在计算过程中修改<代码> 气球_hals
。
首先考虑求助器方法highest_balloon_left
。 这只是确定余下的气球中哪一个是最高的,气球按其阵列指数确定。 例如,如果
heights = [2, 1, 5, 4, 3]
之后
highest_balloon_left(heights)
#=> 2
如下文所示:
heights = [2, 1, 0, 0, 0]
......
highest_balloon_left(heights)
#=> 0
从而成为<条码>[0、0、0、0、0、0]条码>,标志着我们已经结束。
helss = [2, 1, 5, 3]
highest_balloon_left(heights)
#=> 2
之后,我们会发现
heights = [2, 1, 0, 5, 3]
决定
highest_balloon_left(heights)
#=> 3
鉴于所针对的气球(h Salas
),目标为pop_with_shot
shalas[i]
to 0 per balloon i
。
如果halas = [2,1,5,4, 3]
和hightest_left = 2
,这将修改helss
[2, 1, 0, 0, 0]
The variable shots
holds an array, initially empty, that will hold the balloon targeted by each arrow shot (the indices of heights
and balloon_heights
). At the end the size of this array will equal the minimum number of arrays required to shoot down all the balloons.
At each step the highest balloon i
is identified and targeted, i
is appended to shots
and heights[j]
is set to zero for every balloon j
that is shot down by that arrow. The procedure is repeated until height[i]
equals zero for all balloons i
, ...... we are finished, with shots
containing the targeted balloons, in order, with the size of that array equal to the minimum number of arrows required to dispatch all the balloons.