Skip to content

Instantly share code, notes, and snippets.

@Rosuav
Last active January 6, 2017 03:40
Show Gist options
  • Save Rosuav/bfe5dd0629682a52c3b34d466d913cf2 to your computer and use it in GitHub Desktop.
Save Rosuav/bfe5dd0629682a52c3b34d466d913cf2 to your computer and use it in GitHub Desktop.
//Iterative versions of https://gist.github.com/Rosuav/5736378d02c6cd459470582ce301b4b4
//Exercise 1: Take an integer as input, and return a boolean indicating whether
//the value is even or odd.
//Editorial comment: This isn't even iterative, just fomulaic. Exercise 4 could
//be done similarly. Avoiding iteration AND recursion generally gives the best
//performance, when it's possible (but usually it won't be).
function is_even(int) {
return (int % 2) == 0;
}
//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: Obviously arr.map() is the normal way to do this.
function double_all(arr) {
var ret = Array(arr.length);
for (var i = 0; i < arr.length; ++i)
ret[i] = arr[i] * 2;
return ret;
}
//Exercise 3: Take a string as input, reverse the string, and return the new
//string.
//Direct transformation of the tail-recursive form.
function reverse_tail(str) {
var accumulator = "";
while (str !== "") {
accumulator = str[0] + accumulator;
str = str.slice(1);
}
return accumulator;
}
//Exercise 4: Calculates the nth triangular number.
//Should always return n*(n+1)/2
function triangle(n) {
var tot = 0;
for (var i = 1; i <= n; ++i) tot += n;
return tot;
}
//Exercise 5: Split a string based upon a separator (similar to
//String.prototype.split).
//Editorial comment: There are more efficient ways to do this, but this is a
//fairly direct translation of the recursive version.
function split(str, sep) {
var ret = [];
while (true) {
var idx = str.indexOf(sep);
if (idx == -1) break;
ret.push(str.slice(0, idx))
str = str.slice(idx + sep.length);
}
ret.push(str);
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment