# pdcawley/PL101

Added the lesson 0 'homework' for completeness.

• Loading branch information...
pdcawley committed Apr 23, 2012
1 parent 22b2e5b commit 50bcbd4a8f732a7cdfa4b5ae08723f541350b9eb
Showing with 110 additions and 0 deletions.
1. +47 −0 lesson0/treeCounter.coffee
2. +63 −0 lesson0/treeCounter.js
 @@ -0,0 +1,47 @@ +countTree = (tree) -> + countc = (t,n,c) -> + if t? + countc( + t.left + n + 1 + (n) -> + countc( + t.right + n + c + ) + ) + else + c n + ans = 0 + countc tree, 0, (n) -> ans = n + +add_elem = (tree,value) -> + if !tree? + data: value + left: null + right: null + else if value <= tree.data + data: tree.data + left: add_elem tree.left, value + right: tree.right + else + data: tree.data + left: tree.left + right: add_elem tree.right, value + +reduce = (f, init, lst) -> + curr = init + curr = f(curr, val) for val in lst + curr + +create_tree = (lst) -> + reduce( + (tree, elem) -> add_elem(tree, elem), + null, + lst + ) + +console.log countTree null + +console.log countTree create_tree ['b', 'a']
 @@ -0,0 +1,63 @@ +(function() { + var add_elem, countTree, create_tree, reduce; + + countTree = function(tree) { + var ans, countc; + countc = function(t, n, c) { + if (t != null) { + return countc(t.left, n + 1, function(n) { + return countc(t.right, n, c); + }); + } else { + return c(n); + } + }; + ans = 0; + return countc(tree, 0, function(n) { + return ans = n; + }); + }; + + add_elem = function(tree, value) { + if (!(tree != null)) { + return { + data: value, + left: null, + right: null + }; + } else if (value <= tree.data) { + return { + data: tree.data, + left: add_elem(tree.left, value), + right: tree.right + }; + } else { + return { + data: tree.data, + left: tree.left, + right: add_elem(tree.right, value) + }; + } + }; + + reduce = function(f, init, lst) { + var curr, val, _i, _len; + curr = init; + for (_i = 0, _len = lst.length; _i < _len; _i++) { + val = lst[_i]; + curr = f(curr, val); + } + return curr; + }; + + create_tree = function(lst) { + return reduce(function(tree, elem) { + return add_elem(tree, elem); + }, null, lst); + }; + + console.log(countTree(null)); + + console.log(countTree(create_tree(['b', 'a']))); + +}).call(this);

#### 0 comments on commit `50bcbd4`

Please sign in to comment.