Created
September 30, 2012 22:19
-
-
Save joeegan/3808603 to your computer and use it in GitHub Desktop.
javascript recursive sum and max
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
function sumNonRecursive(arr) { | |
var n = 0; | |
for (var i = 0; i < arr.length; i++) { | |
n = n + arr[i]; | |
} | |
return n; | |
} | |
var numArray = [5,2,3]; | |
console.log(sumNonRecursive(numArray)); | |
////////// | |
Array.prototype.head = function(){ | |
return this[0]; | |
}; | |
Array.prototype.last = function(){ | |
if (this.length == 0) { | |
return this; | |
} | |
else { | |
return this[this.length -1]; | |
} | |
}; | |
Array.prototype.tail = function(){ | |
var t = this.splice(0,1); | |
return this; | |
}; | |
function sum(arr) { | |
if (arr.length == 0) { | |
return 0; | |
} | |
else { | |
return arr.head() + sum(arr.tail()); // This line is returned last (arr.head + 0) | |
} | |
} | |
var test = sum([1,2,3,6]); | |
console.log(test); | |
/////////// | |
function max(arr) { | |
if (arr.length == 1) { | |
return arr[0]; | |
} | |
var f = arr.head(); | |
var l = arr.last(); | |
return max(f < l ? arr.slice(1) : arr.slice(0, -1)); | |
} | |
var numbers = [44,46,41,-2,-200,99,124]; | |
console.log(max(numbers)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. This helped me understand recursion in JS! :)