Last active
November 4, 2016 14:00
-
-
Save Dubiy/5a3303146e87c418e42df49c5449d0d9 to your computer and use it in GitHub Desktop.
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
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