Last active
June 27, 2018 08:38
-
-
Save acalpixca/f687059c22e815d82283a2d132209d97 to your computer and use it in GitHub Desktop.
cassidoo challenge 25-06-2018
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
/* | |
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. | |
Example: | |
waterTrap([2,0,2]) | |
> 2 | |
Structure is like this: | |
| | | |
|_| | |
waterTrap({3, 0, 0, 2, 0, 4}) | |
>10 | |
Structure is like this: | |
| | |
| | | |
| | | | |
|__|_| | |
(We can trap 6 units of water between 3 and 2, 1 unit on top of bar 2, and 3 units between 2 | |
and 4) | |
*/ | |
function waterTrap(structure) { | |
if (structure.length<=1) { | |
return(0); | |
} | |
else { | |
// anotar altura de la primera barra | |
var leftHeight=structure[0]; | |
// buscar la siguiente barra más alta o igual que la primera | |
var i=1; | |
while ((i<structure.length) && (structure[i]<leftHeight)) { | |
i++; | |
} | |
// calcular el volumen entre esas dos barras | |
var waterRectangleHeight=structure[i]; | |
if (leftHeight<=structure[i]) { | |
waterRectangleHeight=leftHeight; | |
} | |
var subTotalWater=waterRectangleHeight*(i-1); | |
for (j=1;j<i;j++){ | |
subTotalWater=subTotalWater-structure[j]; | |
} | |
// sumarle el volumen del resto de la estructura a la derecha (llamada recursiva) | |
return(subTotalWater + waterTrap(structure.slice(i,structure.length+1))); | |
} | |
} | |
console.log(waterTrap([])); // result: 0 | |
console.log(waterTrap([5])); // result: 0 | |
console.log(waterTrap([2,0,2])); // result: 2 | |
console.log(waterTrap([3, 0, 0, 2, 0, 4])); // result: 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment