Skip to content

Instantly share code, notes, and snippets.

@chunkzer
Last active August 12, 2020 18:48
Show Gist options
  • Select an option

  • Save chunkzer/f07ea2b653abae46dabb87c03fd3b919 to your computer and use it in GitHub Desktop.

Select an option

Save chunkzer/f07ea2b653abae46dabb87c03fd3b919 to your computer and use it in GitHub Desktop.
// dummy data
const peopleArray = ['Alice', 'Chris', 'Tom Hanks', 'Edgar', 'John'];
// dummy relations
const hardcodedRelations = {
'Chris': {
'John:': true,
'Tom Hanks': true,
},
'John': {
'Alice': true,
'Tom Hanks': true,
},
'Tom Hanks': {},
'Alice': {
'John:': true,
'Tom Hanks': true,
'Chris': true,
},
'Edgar': {
'Tom Hanks': true,
},
}
// string string
const knows = (personA, personB) => hardcodedRelations[personA][personB]
// unique string[]
const celebrityFinder = (people) => {
const couldBeCelebrity = people.reduce((obj, person) => {
obj[person] = true;
return obj;
}, {});
while(Object.keys(couldBeCelebrity).length != 1) {
const [currentNode, ...rest] = Object.keys(couldBeCelebrity);
for(i=0; i<rest.length; i++) {
const knowsX = knows(currentNode, rest[i]);
// if current knowsX current is not celeb. If current doesn't know x, x is not celeb.
knowsX ? delete couldBeCelebrity[currentNode] : delete couldBeCelebrity[rest[i]];
// if current isKnown by x. X is not celeb. If current is not know by x. Current is not celeb.
const isKnownByX = knows(rest[i], currentNode);
isKnownByX ? delete couldBeCelebrity[rest[i]] : delete couldBeCelebrity[currentNode]
}
}
return Object.keys(couldBeCelebrity)[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment