Last active
December 26, 2015 23:59
-
-
Save robertclancy/7234696 to your computer and use it in GitHub Desktop.
A ruby solution for the problem http://qandwhat.apps.runkite.com/i-failed-a-twitter-interview/ using tests from https://gist.github.com/igor47/7228586
This file contains 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
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