// Hunter Schafer, CSE 143 // Prompts the user for two names and prints how distant of friends they are. // This version fixes a couple of bugs. import java.util.*; import java.io.*; public class Friends { public static void main(String[] args) throws FileNotFoundException { Map> friends = buildFriendMap("friends.dot"); System.out.println(friends); Scanner console = new Scanner(System.in); System.out.print("First person? "); String name1 = console.next(); System.out.print("Second person? "); String name2 = console.next(); printLevels(name1, name2, friends); } // prints the friends at each level separating friend1 and friend2 in the // specified friendship graph. // pre: friends contains friend1 private static void printLevels(String name1, String name2, Map> friends) { Set currentLevel = new HashSet(); currentLevel.add(name1); int level = 0; Set visited = new HashSet(); // stop when we found name2 or when we have no more names to explore while (!currentLevel.isEmpty() && !currentLevel.contains(name2)) { // move to the next level level++; visited.addAll(currentLevel); Set nextLevel = new HashSet(); for (String name : currentLevel) { Set friendsOfName = friends.get(name); nextLevel.addAll(friendsOfName); } nextLevel.removeAll(visited); System.out.println("\tDistance " + level + ": " + nextLevel); currentLevel = nextLevel; } if (!currentLevel.isEmpty()) { System.out.println(name2 + " is " + level + " away from " + name1); } else { System.out.println(name2 + " is not connected to " + name1); } } // Builds a map of friendships based on a file with the specified name. // pre: a file named filename exists and is in valid Graphviz format public static Map> buildFriendMap(String filename) throws FileNotFoundException { Scanner input = new Scanner(new File(filename)); // key: names of people // value: Set name's friends Map> friends = new TreeMap>(); while (input.hasNextLine()) { String line = input.nextLine(); if (line.contains("--")) { Scanner lineData = new Scanner(line); String name1 = lineData.next(); lineData.next(); // skip "--" String name2 = lineData.next(); addToFriends(name1, name2, friends); addToFriends(name2, name1, friends); } } return friends; } // Adds name2 to name1's set of friends in the friends map. private static void addToFriends(String name1, String name2, Map> friends) { if (!friends.containsKey(name1)) { friends.put(name1, new TreeSet()); } // assume: there is a mapping for name1 Set name1Friends = friends.get(name1); name1Friends.add(name2); } }