Skip to content

Instantly share code, notes, and snippets.

@fergara
Last active December 27, 2015 02:09
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 fergara/7250590 to your computer and use it in GitHub Desktop.
Save fergara/7250590 to your computer and use it in GitHub Desktop.
Groovy version of the "Calculate Rain Volume" algorithm.
def walls = [ 2, 5, 1, 2, 3, 4, 7, 7, 6 ]
println(calculateVolume(walls))
assert 10 == calculateVolume(walls)
def calculateVolume(land) {
def leftMax = 0
def rightMax = 0
def left = 0
def right = land.size() - 1
def volume = 0
while(left < right) {
if(land[left] > leftMax) {
leftMax = land[left]
}
if(land[right] > rightMax) {
rightMax = land[right]
}
if (leftMax >= rightMax) {
volume += rightMax - land[right]
right--
} else {
volume += leftMax - land[left]
left++
}
}
return volume
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment