mituri

[JS] Ancestors do-while

Jan 5th, 2024
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. /*
  2. Suppose we have some input data describing a graph of relationships between
  3. parents and children over multiple generations. The data is formatted as a
  4. list of (parent, child) pairs, where each individual is assigned a unique
  5. integer identifier.
  6.  
  7. For example, in this diagram, 6 and 8 have common ancestors of 4 and 14.
  8. 14 13
  9. | |
  10. 1 2 4 12
  11. \ / / | \ /
  12. 3 5 8 9
  13. \ / \ \
  14. 6 7 11
  15.  
  16. Write a function that takes the graph, as well as two of the individuals in our
  17. dataset, as its inputs and returns true if and only if they share at least one
  18. ancestor.
  19. */
  20.  
  21. parentChildPairs1 = [
  22. [1, 3], // x -> parent, y -> child
  23. [2, 3],
  24. [3, 6],
  25. [5, 6],
  26. [5, 7],
  27. [4, 5],
  28. [4, 8],
  29. [4, 9],
  30. [9, 11],
  31. [14, 4],
  32. [13, 12],
  33. [12, 9],
  34. ];
  35.  
  36. function hasCommonElement(arr1, arr2) {
  37. return arr1.some((element) => arr2.includes(element));
  38. }
  39.  
  40. function hasCommonAncestor(inputData, a, b) {
  41. const getNextLevelAncestors = (invidual) => {
  42. let parentAncestors = [];
  43.  
  44. inputData.forEach((parentChildPair) => {
  45. const parent = parentChildPair[0];
  46. const child = parentChildPair[1];
  47. if (invidual === child) {
  48. parentAncestors.push(parent);
  49. }
  50. });
  51.  
  52. return parentAncestors;
  53. };
  54.  
  55. const getAllAncestors = (invidual) => {
  56. let ancestors = getNextLevelAncestors(invidual);
  57. let nextAncetors = [];
  58. let finalAncestors = [];
  59.  
  60. do {
  61. nextAncetors = ancestors.reduce((acc, curr) => {
  62. const currAncestors = getNextLevelAncestors(curr);
  63. return [...acc, ...currAncestors];
  64. }, []);
  65.  
  66. ancestors = nextAncetors;
  67. finalAncestors = [...finalAncestors, ...ancestors];
  68. } while (nextAncetors.length !== 0);
  69.  
  70. return finalAncestors;
  71. };
  72.  
  73. return hasCommonElement(getAllAncestors(a), getAllAncestors(b));
  74. }
  75.  
  76. console.log(hasCommonAncestor(parentChildPairs1, 5, 6));
  77.  
  78. // hasCommonAncestor(parentChildPairs1, 3, 8); // => false
  79. // hasCommonAncestor(parentChildPairs1, 5, 8); // => true
  80. // hasCommonAncestor(parentChildPairs1, 6, 8); // => true
  81. // hasCommonAncestor(parentChildPairs1, 6, 9); // => true
  82. // hasCommonAncestor(parentChildPairs1, 1, 3); // => false
  83. // hasCommonAncestor(parentChildPairs1, 3, 1); // => false
  84. // hasCommonAncestor(parentChildPairs1, 7, 11); // => true
  85. // hasCommonAncestor(parentChildPairs1, 6, 5); // => true
  86. // hasCommonAncestor(parentChildPairs1, 5, 6); // => true
  87.  
Advertisement
Add Comment
Please, Sign In to add comment