Skip to content

Instantly share code, notes, and snippets.

@rickosborne
Last active August 29, 2015 14:24
Show Gist options
  • Save rickosborne/c0ec734ab5ca14606fba to your computer and use it in GitHub Desktop.
Save rickosborne/c0ec734ab5ca14606fba to your computer and use it in GitHub Desktop.
function rain(heights) {
var maxHeight = Math.max.apply(Math, heights), rightSide = heights.length - 1;
var left, right, newLeft, newRight;
for (left = 0; heights[left] < maxHeight; left++);
for (right = rightSide; heights[right] < maxHeight; right--);
var pooled = 0;
for (var height = maxHeight; height > 0; height--) {
for (newLeft = left - 1; newLeft >= 0; newLeft--) {
if (heights[newLeft] == height) {
left = newLeft;
}
}
for (newRight = right + 1; newRight <= rightSide; newRight++) {
if (heights[newRight] == height) {
right = newRight;
}
}
for (var i = left + 1; i < right; i++) {
if (heights[i] < height) pooled++;
}
}
console.log(heights, 'pooled', pooled);
return pooled;
}
// rain([1,4,2,5,1,2,3]);
// rain([1, 2, 3, 2, 1]);
function linear_rain(heights) {
var right = heights.length - 1, left = 0, pooled = 0, tallest, currentIndex, currentHeight, direction = 1, steps = 0;
while (left < right) {
// trim off the ends so that everything in the middle is going to pool
while ((left < right) && (heights[left] <= heights[left + 1])) { left++; steps++; }
while ((right > left) && (heights[right] <= heights[right - 1])) { right--; steps++; }
if (left < right) {
if (heights[left] < heights[right]) { // move left to right
direction = 1;
currentIndex = left;
} else {
direction = -1;
currentIndex = right;
}
tallest = heights[currentIndex];
while (left < right) {
steps++;
if (direction == 1) left++;
else right--;
currentIndex += direction;
currentHeight = heights[currentIndex];
if (currentHeight < tallest) {
pooled += tallest - currentHeight;
} else if (currentHeight > tallest) {
tallest = currentHeight;
break;
}
}
}
}
console.log('pooled', pooled, 'from', heights, 'in', steps, 'steps');
return pooled;
}
linear_rain([1,4,2,5,1,2,3]);
linear_rain([1, 2, 3, 2, 1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment