Skip to content

Instantly share code, notes, and snippets.

@steve-taylor
Created September 27, 2012 15:59
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 steve-taylor/3794803 to your computer and use it in GitHub Desktop.
Save steve-taylor/3794803 to your computer and use it in GitHub Desktop.
Grand final
import java.util.*;
public class Challenge {
public static void main(String[] args) throws Exception {
// Build map.
Map<String,Set<String>> graph = new HashMap<String,Set<String>>();
for (String rel : Input.read().split("\\,")) {
String[] toks = rel.split("\\-");
Set<String> friends = graph.containsKey(toks[0]) ? graph.get(toks[0]) : new HashSet<String>();
graph.put(toks[0], friends);
friends.add(toks[1]);
friends = graph.containsKey(toks[1]) ? graph.get(toks[1]) : new HashSet<String>();
graph.put(toks[1], friends);
friends.add(toks[0]);
}
Set<String> fofs = new HashSet<String>();
// For everyone other than John
for (Map.Entry<String,Set<String>> entry : graph.entrySet()) {
if (entry.getKey().equals("1")) {
continue;
}
Set<String> common = new HashSet<String>(graph.get("1"));
common.retainAll(entry.getValue());
if (common.size() == 1) {
fofs.add(entry.getKey());
}
}
List<String> fofList = new ArrayList<String>(fofs);
Collections.sort(fofList);
StringBuilder sb = new StringBuilder();
for (String f : fofList) {
sb.append(",").append(f);
}
Output.write(sb.substring(1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment