From a2ff7b545c1f1dce06040fd3954876c2e8cb49bf Mon Sep 17 00:00:00 2001 From: chirvasitua Date: Mon, 17 May 2021 21:58:03 -0400 Subject: 1st commit on 113_node --- challenge-113/stuart-little/node/ch-2.js | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100755 challenge-113/stuart-little/node/ch-2.js (limited to 'challenge-113/stuart-little/node/ch-2.js') 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