Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Suppose we have some input data describing a graph of relationships between
- parents and children over multiple generations. The data is formatted as a
- list of (parent, child) pairs, where each individual is assigned a unique
- integer identifier.
- For example, in this diagram, 6 and 8 have common ancestors of 4 and 14.
- 14 13
- | |
- 1 2 4 12
- \ / / | \ /
- 3 5 8 9
- \ / \ \
- 6 7 11
- Write a function that takes the graph, as well as two of the individuals in our
- dataset, as its inputs and returns true if and only if they share at least one
- ancestor.
- */
- parentChildPairs1 = [
- [1, 3], // x -> parent, y -> child
- [2, 3],
- [3, 6],
- [5, 6],
- [5, 7],
- [4, 5],
- [4, 8],
- [4, 9],
- [9, 11],
- [14, 4],
- [13, 12],
- [12, 9],
- ];
- function hasCommonElement(arr1, arr2) {
- return arr1.some((element) => arr2.includes(element));
- }
- function hasCommonAncestor(inputData, a, b) {
- const getNextLevelAncestors = (invidual) => {
- let parentAncestors = [];
- inputData.forEach((parentChildPair) => {
- const parent = parentChildPair[0];
- const child = parentChildPair[1];
- if (invidual === child) {
- parentAncestors.push(parent);
- }
- });
- return parentAncestors;
- };
- const getAllAncestors = (invidual) => {
- let ancestors = getNextLevelAncestors(invidual);
- let nextAncetors = [];
- let finalAncestors = [];
- do {
- nextAncetors = ancestors.reduce((acc, curr) => {
- const currAncestors = getNextLevelAncestors(curr);
- return [...acc, ...currAncestors];
- }, []);
- ancestors = nextAncetors;
- finalAncestors = [...finalAncestors, ...ancestors];
- } while (nextAncetors.length !== 0);
- return finalAncestors;
- };
- return hasCommonElement(getAllAncestors(a), getAllAncestors(b));
- }
- console.log(hasCommonAncestor(parentChildPairs1, 5, 6));
- // hasCommonAncestor(parentChildPairs1, 3, 8); // => false
- // hasCommonAncestor(parentChildPairs1, 5, 8); // => true
- // hasCommonAncestor(parentChildPairs1, 6, 8); // => true
- // hasCommonAncestor(parentChildPairs1, 6, 9); // => true
- // hasCommonAncestor(parentChildPairs1, 1, 3); // => false
- // hasCommonAncestor(parentChildPairs1, 3, 1); // => false
- // hasCommonAncestor(parentChildPairs1, 7, 11); // => true
- // hasCommonAncestor(parentChildPairs1, 6, 5); // => true
- // hasCommonAncestor(parentChildPairs1, 5, 6); // => true
Advertisement
Add Comment
Please, Sign In to add comment