aboutsummaryrefslogtreecommitdiff
path: root/challenge-113/stuart-little/node/ch-2.js
diff options
context:
space:
mode:
authorchirvasitua <stuart-little@users.noreply.github.com>2021-05-17 21:58:03 -0400
committerchirvasitua <stuart-little@users.noreply.github.com>2021-05-17 23:45:15 -0400
commita2ff7b545c1f1dce06040fd3954876c2e8cb49bf (patch)
tree4162ac6dd0f6545f89a091d9b0a7ab8df69e0652 /challenge-113/stuart-little/node/ch-2.js
parentc3cd45087006d3f63b05219b8280a25dc1ea7ba9 (diff)
downloadperlweeklychallenge-club-a2ff7b545c1f1dce06040fd3954876c2e8cb49bf.tar.gz
perlweeklychallenge-club-a2ff7b545c1f1dce06040fd3954876c2e8cb49bf.tar.bz2
perlweeklychallenge-club-a2ff7b545c1f1dce06040fd3954876c2e8cb49bf.zip
1st commit on 113_node
Diffstat (limited to 'challenge-113/stuart-little/node/ch-2.js')
-rwxr-xr-xchallenge-113/stuart-little/node/ch-2.js49
1 files changed, 49 insertions, 0 deletions
diff --git a/challenge-113/stuart-little/node/ch-2.js b/challenge-113/stuart-little/node/ch-2.js
new file mode 100755
index 0000000000..2364b0a3a8
--- /dev/null
+++ b/challenge-113/stuart-little/node/ch-2.js
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+
+const printTree = require('print-tree');
+
+function split2trees(lst) {
+ ix = [...lst.keys()].find(i => 2*lst.slice(0,i+1).filter(x => x === ".").length > i+1 );
+ return [lst.slice(0,ix+1), lst.slice(ix+1)]
+}
+
+function mkTree(lst) {
+ if (lst[0] === ".") {
+ return { name: "" };
+ };
+ const nm = lst[0];
+ const [lft,rght] = split2trees(lst.slice(1));
+ return {
+ name: nm,
+ children: [mkTree(lft),mkTree(rght)],
+ };
+}
+
+const inTreeList = (process.argv.length > 2) ? (process.argv.slice(2)) : (["1", "2", "4", ".", "7", ".", ".", ".", "3", "5", ".", ".", "6", ".", "."]);
+const sm = inTreeList.reduce((acc,el) => {return acc + (parseInt(el) || 0)}, 0);
+const outTreeList = inTreeList.map(x => (parseInt(x)) ? (sm - parseInt(x)) : x);
+
+printTree(
+ mkTree(outTreeList),
+ node => node.name.toString(),
+ node => node.children,
+);
+
+/*
+run <script> <tree in preorder form with '.' for empty nodes, entered as space-separated values>
+
+ref: https://stackoverflow.com/a/2676849/11064961
+
+e.g. 1 2 4 . 7 . . . 3 5 . . 6 . . represents the tree
+
+ 1
+ / \
+ 2 3
+ / / \
+ 4 5 6
+ \
+ 7
+
+given as an example in the problem formulation at https://perlweeklychallenge.org/blog/perl-weekly-challenge-113/#TASK2
+*/
+