aboutsummaryrefslogtreecommitdiff
path: root/challenge-113/stuart-little/node/ch-2.js
diff options
context:
space:
mode:
authordrbaggy <js5@sanger.ac.uk>2021-05-18 22:19:52 +0100
committerdrbaggy <js5@sanger.ac.uk>2021-05-18 22:19:52 +0100
commitd8828a6cfbadb2f453508a4390777534ab4e5dca (patch)
tree777df3bd09f6988996d50aeefe21bd757cf57041 /challenge-113/stuart-little/node/ch-2.js
parentacf7efe3c26276e986c039273f2df7179de5ab24 (diff)
parent28e8ae0a51e27c2435ca1e8fc16f4eea32a78b05 (diff)
downloadperlweeklychallenge-club-d8828a6cfbadb2f453508a4390777534ab4e5dca.tar.gz
perlweeklychallenge-club-d8828a6cfbadb2f453508a4390777534ab4e5dca.tar.bz2
perlweeklychallenge-club-d8828a6cfbadb2f453508a4390777534ab4e5dca.zip
Merge remote-tracking branch 'upstream/master'
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
+*/
+