I have a problem with exiting the loop after finding the maximum value in array.
The job is:
Pyramids #1 Let's consider and array p of length n filled with unique numbers from (1..n) range - for example p=[1,3,4,2,5] (n=5)
Each number represents height of a pyramid. Assuming, that lower pyramid placed behind the higher pyramid is not visible determine how many pyramids are visible from the beginning (left side), and the end (right side) of the given array. Return result as a hash formatted as follows: {left: x, right: y}
Example 1: Input: p = [1,2,3,4,5]
Output: { left: 5, right: 1 }
Explanation: From the left side we can see all 5 pyramids, while from the right side we can only see the highest one
Example 2: Input: p = [4,5,1,2,3]
Output: { left: 2, right: 2 }
Explanation: From left side we can see 4, and 5; from right: 5 and 3
My code:
array = [4,5,1,2,3]
left = 1
array.each_cons(2) do |first, second|
if first < second
left = 1
end
end
right = 1
array.reverse.each_cons(2) do |first, second|
if first < second
right = 1
end
end
puts hash = {left: left, right: right}
I need to break the loop after finding array.max and don't increase the iterator.
Do you have any ideas?
CodePudding user response:
I don't believe the fundamental problem is exiting the loop, but is with the calculation being performed.
Suppose
p = [4,5,1,2,3,6,5]
Here is a drawing of what the observer sees when viewing the buildings from the left
[4,5,1,2,3,6,5]
■
0 -> ■ ■ ■
| ■ ■ ■ ■
^ ■ ■ ■ ■ ■
| ■ ■ ■ ■ ■ ■
^ ■ ■ ■ ■ ■ ■ ■
When viewed from the left the buildings at offsets 0
, 1
and 5
(with respective heights of 4
, 5
and 6
) are visible. When viewed from the right the buildings at offset 6
and 5
(with respective heights of 5
and 6
) are visible.
Note that a building is visible if and only if it is taller than all the buildings between it and the observer. We therefore may compute the number of buildings visible when viewed from the left as follows.
def visible_from_left(p)
mx = 0
p.count do |x|
tf = x > mx
mx = [mx, x].max
tf
end
end
visible_from_left(p)
#=> 3
See Array#count.
To determine the number of buildings visible from the right we may simply use visible_from_left
with p.reverse
as its argument.
def visible_from_right(p)
visible_from_left(p.reverse)
end
visible_from_right(p)
#=> 2