// 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 { Scanner input = new Scanner(new File("friends.dot")); Map> friends = readFile(input); for (String person : friends.keySet()) { System.out.println(person + " " + friends.get(person)); } } // pre : Assumes the given input is set to read a valid GraphViz file // post: Records all of the friendships listed in the given file and returns // it as a Map where the keys are each person, and the values are the set of all // their friends. Friendships are bi-directional so every record of "A is friends with B" // will also have an added "B is friends with A" public static Map> readFile(Scanner input) { 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(); addFriendship(friends, name1, name2); addFriendship(friends, name2, name1); } } return friends; } // Adds name2 to the friends for name1 (creating a new set of friends if name1 has none) public static void addFriendship(Map> friends, String name1, String name2) { if (!friends.containsKey(name1)) { Set theFriends = new TreeSet(); theFriends.add(name2); friends.put(name1, theFriends); } else { Set theFriends = friends.get(name1); theFriends.add(name2); // Hunter: Not necessary, because the value (the reference to the set) // is already in the map! // friends.put(name1, theFriends); } } }