Skip to content

Instantly share code, notes, and snippets.

@robertclancy
Last active December 26, 2015 23:59
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 robertclancy/7234696 to your computer and use it in GitHub Desktop.
Save robertclancy/7234696 to your computer and use it in GitHub Desktop.
def water(x)
water_acc(x, 0, 0, 0)
end
def water_acc(a, left, right, total)
if a.empty?
total
else
if left <= right
x, *xs = a
if x < left
water_acc(xs, left, right, total + left - x)
else
water_acc(xs, x, right, total)
end
else
*ys, y = a
if y < right
water_acc(ys, left, right, total + right - y)
else
water_acc(ys, left, y, total)
end
end
end
end
if __FILE__ == $0
tests = [
[[1,0,1], 1],
[[2,0,1], 1],
[[5,0,5], 5],
[[0,1,0,1,0], 1],
[[1,0,1,0], 1],
[[1,0,1,2,0,2], 3],
[[2,5,1,2,3,4,7,7,6], 10],
[[5,1,0,1,], 1],
[[2,5,1,2,3,4,7,7,6,3,5], 12],
[[2,5,1,3,1,2,1,7,5,6], 18]
]
tests.each do |x, v|
if (water(x) == v)
puts "TRUE: #{x}, #{v}"
else
puts "MISMATCH: #{x}, expected #{v} got #{water(x)}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment