3 ms·
My results: Array.prototype.contains = function(obj) { // copied from http://stackoverflow.com/questions/237104/javascript-array-containsobj var i =
by justinlilly 16y ago
My results:
Array.prototype.contains = function(obj) {
// copied from http://stackoverflow.com/questions/237104/javascript-array-containsobj
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
function doTree (node, func) {
var seen = [];
var to_see = [node];
while to_see.length {
var next_node = to_see.pop();
func(next_node.value);
seen.push(next_node);
for (var i; i < next_node.children.length; i++) {
var child = next_node.children[i];
if (! seen.contains(child) && ! to_see.contains(child)) {
to_see.push(child);
}
}
}
}
// --
var num_arr = [];
var sum = 0;
doTree(numTree, function (val) { num_arr.push(val); })
// googled for a sum function. didn't know if javascript had map or reduce in stdlib.
for (var i; num_arr.length; i++) {
sum += num_arr[i];
}
// sum is sum.
// --
5-10 min.
// --
its kind of a pain to do in a text box. variable width fonts make it harder to read. Would have also been nice to have an actual javascript repl. Was a bit shaky on tree traversal, but I think that's correct. Also not intimately familiar with javascript stdlib.
- orangecat 16y agoWould have also been nice to have an actual javascript repl. Chrome has it built in and Firefox has Firebug. Was a bit shaky on tree traversal, but I think that's correct. It's much simpler with recursion. Your contains method is "correct" but doesn't work in this case because objects with the same keys and values still aren't necessarily equal.
- ydant 16y agoRecursion is also what the "exam" asked for, so I imagine you'd be dinged a bit for not using it.
- jiaaro 16y agowow... mine were much shorter than that. Maybe I did it wrong? var doTree = function doTree(node, fn) { for (var i = 0; i < node.children.length; i++) { doTree(node.children[i]); } fn(node.value); } var treeSum = 0; doTree(numTree, function(nodeValue) { treeSum += nodeValue; }); edit: fixed a dumb bug edit2: nicer coding style
- justinlilly 16y agoNope. That's correct as well. Recursion is a much more elegant way of doing it. :-/
- kqr2 16y agoShould the last line be: doTree(numTree, addNodeToSum)
- jiaaro 16y agooh you're right!
- gcr 16y agoWow... you got... erm. something very different than I did. function mapTree(tree, fun) { // apply function to tree.value, then recurse (needs javascript.map) if (typeof tree == 'undefined') { return null; } return { value: fun(tree.value), children: tree.children.map( function(tree) { return mapTree(tree, fun); }) }; } ////////////////// var numTree={value: 42, children: [ {value: 43, children: []}, {value: 44, children: [{value: 95, children: []}, {value: 1, children: []}]} ] }; var count=0; mapTree(numTree, function(c) { count+=c; }); alert(count); // => 225
- jcromartie 16y agoOverachiever :D