Last active
January 13, 2020 21:40
-
-
Save pakman198/7f6484633d7873624dee742eb6f78728 to your computer and use it in GitHub Desktop.
Coding Exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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, 3 is a child of 1 and 2, and 5 is a child of 4: | |
1 2 4 | |
\ / / \ | |
3 5 8 | |
\ / \ \ | |
6 7 10 | |
Write a function that takes this data as input and returns two collections: one containing all individuals with zero | |
known parents, and one containing all individuals with exactly one known parent. | |
var parentChildPairs = [ | |
[1, 3], [2, 3], [3, 6], [5, 6], | |
[5, 7], [4, 5], [4, 8], [8, 10] | |
]; | |
Sample output (pseudodata): | |
findNodesWithZeroAndOneParents(parentChildPairs) => [ | |
[1, 2, 4], // Individuals with zero parents | |
[5, 7, 8, 10] // Individuals with exactly one parent | |
] | |
*/ | |
function findNodesWithZeroAndOneParents(family) { | |
const parents = family.map(a => a[0]); | |
const children = family.map(a => a[1]); | |
const singleParentChildren = family.reduce((acc, curr, index) => { | |
if(index === 0) { | |
return acc.concat(curr[1]); | |
} | |
if(curr[1] === family[index-1][1] ){ | |
acc.pop(); | |
return acc; | |
} else { | |
return acc.concat(curr[1]); | |
} | |
}, []); | |
const doubleParentChildren = children.filter(child => !singleParentChildren.includes(child)); | |
const individuals = [...new Set(parents), ...new Set(children)]; | |
const uniqueIndividuals = new Set(individuals); | |
const zeroParentChildren = Array.from(uniqueIndividuals).filter(i => { | |
if(!singleParentChildren.includes(i) && !doubleParentChildren.includes(i)) { | |
return i; | |
} | |
return; | |
}); | |
console.log({parents, children, singleParentChildren, doubleParentChildren, uniqueIndividuals, zeroParentChildren}) | |
} | |
findNodesWithZeroAndOneParents(parentChildPairs) |
The final round:
function findNodesWithZeroAndOneParents(family) {
let parents = new Set(),
children = new Set(),
multiParentChildren = new Set();
for(let individual of family) {
let [parent, child] = individual;
if (children.has(child)) {
multiParentChildren.add(child);
}
parents.add(parent);
children.add(child);
}
console.log({parents, children, multiParentChildren})
zeroParents = [...parents].filter(ch => !children.has(ch))
oneParent = [...children].filter(ch => !multiParentChildren.has(ch))
console.log(zeroParents);
console.log(oneParent);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Second solution: