Skip to content

Instantly share code, notes, and snippets.

@Dubiy
Last active November 4, 2016 14:00
Show Gist options
  • Save Dubiy/5a3303146e87c418e42df49c5449d0d9 to your computer and use it in GitHub Desktop.
Save Dubiy/5a3303146e87c418e42df49c5449d0d9 to your computer and use it in GitHub Desktop.
var arr = [2,1,5,0,3,4,7,2,3,1,0];
console.log('waterRecursion', findWater(arr, Math.min(...arr), Math.max(...arr)));
///////////////////////////////////////////////////////////////////////////////
var depth = Math.min(...arr);
var maxHigh = Math.max(...arr);
var water = 0;
while (depth <= maxHigh) {
for (var idx = 0; idx < arr.length; idx++) {
if (arr[idx] <= depth) {
if (checkForWater(idx, depth, arr)) {
water++;
}
}
}
depth++;
}
console.log('water', water);
///////////////////////////////////////////////////////////////////////////////
function checkForWater(idx, depth, arr) {
for (var i = idx; i < arr.length; i++) {
if (arr[i] > depth) {
for (var j = idx; j >= 0; j--) {
if (arr[j] > depth) {
return true;
}
}
break;
}
}
return false;
}
function findWater(arr, depth, maxHigh) {
var res = arr.reduce(function (total, currentValue, currentIndex, arr) {
if (currentValue <= depth) {
var testDepth = function (el) {
return el > depth;
};
var testLeft = arr.slice(0, currentIndex + 1).some(testDepth);
var testRight = arr.slice(currentIndex).some(testDepth);
if (testLeft && testRight) {
return total + 1;
}
}
return total;
}, 0);
if (depth < maxHigh) {
return res + findWater(arr, depth + 1, maxHigh);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment