Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created June 13, 2017 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/8b9e766261890b78e849d162efcf82a1 to your computer and use it in GitHub Desktop.
Save yokolet/8b9e766261890b78e849d162efcf82a1 to your computer and use it in GitHub Desktop.
import java.util.*;
public class FindTheCelebrity {
static int N = 7;
static Map<Integer, List<Integer>> relation = new HashMap();
static {
relation.put(0, Arrays.asList(1));
relation.put(1, new ArrayList()); // celebrity
relation.put(2, Arrays.asList(1));
relation.put(3, Arrays.asList(1, 2));
relation.put(4, Arrays.asList(1));
relation.put(5, Arrays.asList(1));
relation.put(6, Arrays.asList(1, 5));
}
static boolean knows(int a, int b) {
return relation.get(a).contains(b);
}
static int findCelebrity() {
Stack<Integer> stack = new Stack();
for (int i = 0; i < N; i++) {
stack.push(i);
}
// elimination
while (stack.size() > 1) {
int a = stack.pop();
int b = stack.pop();
if (knows(a, b)) {
// a knows b
// b is a potential celeb
// make b back to stack
stack.push(b);
} else {
// a doesn't knows b
// a is a potential celeb
// make a back to stack
stack.push(a);
}
}
int c = stack.pop();
// verification
for (int i = 0; i < N; i++) {
if ((i != c) && (knows(c, i) || !knows(i, c))) {
return -1;
}
}
return c;
}
public static void main(String[] args) {
System.out.println(findCelebrity());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment