Created
October 31, 2013 16:43
-
-
Save pencilcheck/7252934 to your computer and use it in GitHub Desktop.
This solution does one pass and gives all the water between all the puddles found in the shape given
This file contains hidden or 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
shape = [1, 0, 3, 4, 5, 3, 2, 4, 6, 8] | |
puddles = [0] | |
current_puddle = 0 | |
left = nil | |
right = nil | |
has_right_wall = false | |
shape.each do |height| | |
left = height if not left | |
right = height | |
if right < left | |
puddles[current_puddle] += left - right | |
has_right_wall = false | |
else | |
current_puddle += 1 | |
puddles[current_puddle] = 0 | |
left = right | |
has_right_wall = true | |
end | |
end | |
unless has_right_wall | |
puddles[current_puddle] = 0 | |
end | |
p puddles.reduce(0) {|memo, water| memo += water; memo} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment