Skip to content

Instantly share code, notes, and snippets.

@pencilcheck
Created October 31, 2013 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pencilcheck/7252934 to your computer and use it in GitHub Desktop.
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
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