Skip to content

Instantly share code, notes, and snippets.

@sourcepirate
Created May 29, 2018 02:47
Show Gist options
  • Select an option

  • Save sourcepirate/f640061c392f5ac7608c73171b866c42 to your computer and use it in GitHub Desktop.

Select an option

Save sourcepirate/f640061c392f5ac7608c73171b866c42 to your computer and use it in GitHub Desktop.

const data = [
  ["a", "b"],
  ["b", "c"],
  ["a", "d"],
  ["d", "e"],
  ["d", "c"]
];

function analyse(root, graph) {
  let tree = {};
  // build a graph with adacency list
  for(let g of graph) {
    if(!(g[0] in tree)){
      tree[g[0]] = [g[1]];
    } else {
      tree[g[0]].push(g[1]);
    }
  }
  console.log(tree);

  // compute the total friend connections.
  let rootNode = tree[root];
  let degree = {};
  for(let friendNode of rootNode) {
    console.log(`Finding friend of: ${friendNode}`);
    for(let hisFriend of tree[friendNode]) {
      if(!(hisFriend in degree)){
        degree[hisFriend] = 1
      } else {
        degree[hisFriend] += 1;
      }
    }
  }

 return degree;
}

const suggestions = analyse("a", data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment