Skip to content

Instantly share code, notes, and snippets.

@pfiller
Last active August 29, 2015 14:10
Show Gist options
  • Save pfiller/72df78169bca9dfaa1dd to your computer and use it in GitHub Desktop.
Save pfiller/72df78169bca9dfaa1dd to your computer and use it in GitHub Desktop.
(function(window){
function sum_peaked_array(peaked_array){
var lowest_array_peak, sum = 0;
lowest_array_peak = Math.min(peaked_array[0],peaked_array[peaked_array.length-1]);
for(var i=1; i<peaked_array.length-1; i+=1){
sum += lowest_array_peak - peaked_array[i];
}
return sum;
}
window.sum_array_valleys = function(input_array){
var total = 0, right_peak_index = 1;
for(var i=1; i<input_array.length; i+=1){
if(input_array[i] >= input_array[0]){
right_peak_index = i;
break;
}
else if(input_array[i] > input_array[right_peak_index]){
right_peak_index = i;
}
}
total = right_peak_index > 1 ? sum_peaked_array(input_array.slice(0, right_peak_index+1)) : 0;
if(right_peak_index < input_array.length){
return total + sum_array_valleys(input_array.splice(right_peak_index))
}
else{
return total;
}
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment