Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var data = document.body.textContent.split(/\n/).map(x => {
  2.     const name = x.split(' ')[0];
  3.     const weight = parseInt(x.split(/\(/)[1],10);
  4.     const children = ((x.match(/ -> (.+)$/) ?? [])[1] ?? '').split(/, /).filter(x => x);
  5.     return { name, weight, children };
  6. });
  7.  
  8. var children = data.flatMap(x => x.children).flat();
  9. var root = data.find(x => children.indexOf(x.name) === -1);
  10. console.log('Answer #1:', root.name);
  11.  
  12. var groups = { };
  13. data.forEach(c => groups[c.name] = c);
  14.  
  15. var tree = { node: root, children: [ ] };
  16. var queue = [ tree ];
  17. while (queue.length > 0) {
  18.     const next = queue.shift();
  19.     next.children = next.node.children.map(n => ({ node: groups[n], children: [ ] }));
  20.     queue.push(...next.children);
  21. }
  22.  
  23. var weigh = (tree) => {
  24.     tree.weight = tree.node.weight + tree.children.reduce((p,n) => p + weigh(n), 0);
  25.     return tree.weight;
  26. };
  27. weigh(tree);
  28.  
  29. var find = (tree, previous) => {
  30.     const right = tree.children.find((x,n,a) => x.weight === a[n + 1].weight);
  31.     const wrong = tree.children.find((x,n,a) => x.weight !== right.weight);
  32.     if (wrong) find(wrong, right);
  33.     else console.log('Answer #2:', tree.node.weight - (tree.weight - previous.weight));
  34. };
  35. find(tree);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement