Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var data = document.body.textContent.split(/\n/).map(x => {
- const name = x.split(' ')[0];
- const weight = parseInt(x.split(/\(/)[1],10);
- const children = ((x.match(/ -> (.+)$/) ?? [])[1] ?? '').split(/, /).filter(x => x);
- return { name, weight, children };
- });
- var children = data.flatMap(x => x.children).flat();
- var root = data.find(x => children.indexOf(x.name) === -1);
- console.log('Answer #1:', root.name);
- var groups = { };
- data.forEach(c => groups[c.name] = c);
- var tree = { node: root, children: [ ] };
- var queue = [ tree ];
- while (queue.length > 0) {
- const next = queue.shift();
- next.children = next.node.children.map(n => ({ node: groups[n], children: [ ] }));
- queue.push(...next.children);
- }
- var weigh = (tree) => {
- tree.weight = tree.node.weight + tree.children.reduce((p,n) => p + weigh(n), 0);
- return tree.weight;
- };
- weigh(tree);
- var find = (tree, previous) => {
- const right = tree.children.find((x,n,a) => x.weight === a[n + 1].weight);
- const wrong = tree.children.find((x,n,a) => x.weight !== right.weight);
- if (wrong) find(wrong, right);
- else console.log('Answer #2:', tree.node.weight - (tree.weight - previous.weight));
- };
- find(tree);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement