Created
May 16, 2021 21:17
-
-
Save kaisnb/c8fdb08aafd9bb11b2ec8a1f926e5476 to your computer and use it in GitHub Desktop.
JavaScript Celebrity Identification Problem
This file contains 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
class Person { | |
name; | |
knownPersons = new Set(); | |
constructor(name) { | |
this.name = name; | |
} | |
add(person) { | |
this.knownPersons.add(person); | |
} | |
knows(person) { | |
return this.knownPersons.has(person); | |
} | |
toString() { | |
return this.name; | |
} | |
} | |
const p1 = new Person('Michael Schumacher'); | |
const p2 = new Person('Max Mustermann'); | |
const p3 = new Person('Wolfgang Prety'); | |
const p4 = new Person('Udo Jürgens'); | |
p1.add(p2); | |
p1.add(p3); | |
p1.add(p4); | |
p3.add(p2); | |
p3.add(p1); | |
p4.add(p2); | |
p4.add(p3); | |
const findCelebrity = people => { | |
const stack = [...people]; | |
// Elimination phsae | |
while (stack.length > 1) { | |
const a = stack.pop(); | |
const b = stack.pop(); | |
if (a.knows(b)) { | |
stack.push(b); | |
} else { | |
stack.push(a); | |
} | |
} | |
// Verification phase | |
const candidate = stack[0]; | |
for (let i = 0; i < people.length; i++) { | |
const person = people[i]; | |
if ( | |
candidate != person && | |
(candidate.knows(person) || !person.knows(candidate)) | |
) { | |
return null; | |
} | |
} | |
return candidate; | |
}; | |
const celebrity = findCelebrity([p1, p2, p3, p4]); | |
console.log(celebrity ? celebrity.toString() : 'No celebrity found'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment