Last active
October 24, 2016 20:02
-
-
Save Rosuav/5736378d02c6cd459470582ce301b4b4 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
//Exercise 1: Take an integer as input, and return a boolean indicating whether | |
//the value is even or odd. | |
function is_even(int) { | |
if (int < 0) return is_even(-int); | |
if (int < 2) return !int; | |
return is_even(int - 2); | |
} | |
//Exercise 2: Take an array as input which contains an unknown set of numbers, | |
//and output an array which doubles the values of each item in that array. Test | |
//your solution by trying a handful of different arrays. Don't worry about | |
//error checking to make sure that the array you're given is valid input. | |
//Editorial comment: This function is conceptually correct, but abysmally slow. | |
function double_all(arr) { | |
if (!arr.length) return []; | |
return [arr[0] * 2].concat(double_all(arr.slice(1))); | |
} | |
//Editorial comment: This version of the algorithm operates in place, and can | |
//operate on a subset of an array. | |
function double_all_inplace(arr, start) { | |
start |= 0; | |
if (start >= arr.length) return arr; | |
arr[start] *= 2; | |
return double_all_inplace(arr, start + 1); | |
} | |
//Exercise 3: Take a string as input, reverse the string, and return the new | |
//string. | |
function reverse(str) { | |
//if (str == "able was i ere i saw elba") return str; //Base case | |
if (str.length < 2) return str; | |
return reverse(str.slice(1)) + str[0]; | |
} | |
//Tail-recursive version of the above | |
function reverse_tail(str, accumulator) { | |
accumulator = accumulator || ""; | |
if (str === "") return accumulator; | |
return reverse_tail(str.slice(1), str[0] + accumulator) | |
} | |
//Exercise 4: Calculates the nth triangular number. | |
//Should always return n*(n+1)/2 | |
function triangle(n) { | |
if (n < 2) return n; | |
return n + triangle(n - 1); | |
} | |
//Exercise 5: Split a string based upon a separator (similar to | |
//String.prototype.split). | |
function split(str, sep) { | |
var idx = str.indexOf(sep); | |
if (idx == -1) return [str]; | |
return [str.slice(0, idx)].concat(split(str.slice(idx + sep.length), sep)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment