Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added the lesson 0 'homework' for completeness.

  • Loading branch information...
commit 50bcbd4a8f732a7cdfa4b5ae08723f541350b9eb 1 parent 22b2e5b
@pdcawley authored
Showing with 110 additions and 0 deletions.
  1. +47 −0 lesson0/treeCounter.coffee
  2. +63 −0 lesson0/treeCounter.js
View
47 lesson0/treeCounter.coffee
@@ -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']
View
63 lesson0/treeCounter.js
@@ -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);
Please sign in to comment.
Something went wrong with that request. Please try again.