// This program reads a Graphviz file of friendships and finds the distance // between two people in the graph. import java.util.*; import java.io.*; public class Friends { public static void main(String[] args) throws FileNotFoundException { Scanner console = new Scanner(System.in); System.out.print("Input file? "); String fileName = console.nextLine(); Scanner input = new Scanner(new File(fileName)); Map> friends = processFriends(input); // outputFriends(friends); System.out.print("Starting person? "); String origin = console.nextLine().trim(); if (!friends.containsKey(origin)) { System.out.println("That person is not in the data file."); } else { System.out.print("Person to find? "); String dest = console.nextLine().trim(); findFriend(friends, origin, dest); } } // pre: input is open and contains a legal Graphviz file of friendships // returns a map from each person in the file to their set of friends public static Map> processFriends(Scanner input) { Map> friends = new TreeMap>(); while (input.hasNextLine()) { String line = input.nextLine(); if (line.contains("--")) { String[] parts = line.split("--"); addFriend(friends, parts[0].trim(), parts[1].trim()); addFriend(friends, parts[1].trim(), parts[0].trim()); } } return friends; } // pre: friendMap is non-null // creates a friendship link in friendMap from friend1 to friend2 private static void addFriend(Map> friendMap, String friend1, String friend2) { if (!friendMap.containsKey(friend1)) { friendMap.put(friend1, new TreeSet()); } friendMap.get(friend1).add(friend2); } public static void outputFriends(Map> friendMap) { for (String name : friendMap.keySet()) { System.out.println(name + " is friends with " + friendMap.get(name)); } } // pre: friendMap is non-null // origin is a kay in friendMap // prints out the list of friends each distance from origin until either // target is found or no more people are reachable public static void findFriend(Map> friendMap, String origin, String target) { System.out.println(origin + "'s friends:"); Set oldFriends = new TreeSet(); Set newFriends = new TreeSet(); newFriends.add(origin); int level = 0; while (!newFriends.contains(target) && !newFriends.isEmpty()) { oldFriends.addAll(newFriends); level++; Set newNewFriends = new TreeSet(); for (String person : newFriends) { newNewFriends.addAll(friendMap.get(person)); } newNewFriends.removeAll(oldFriends); newFriends = newNewFriends; System.out.println(" Level " + level + ": " + newFriends); } if (newFriends.contains(target)) { System.out.println(target + " found at level " + level); } else { System.out.println(target + " not found"); } } }