// 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 { System.out.println("Welcome to the cse143 friend finder."); Map> friends = readFile("friends.dot"); System.out.println(friends); Scanner console = new Scanner(System.in); System.out.print("starting name? "); String name1 = console.next(); if (!friends.containsKey(name1)) { System.out.println("That person is not in the data file."); } else { System.out.print("target name? "); String name2 = console.next(); if (!friends.containsKey(name2)) { System.out.println("That person is not in the data file."); } else { findFriends(friends, name1, name2); } } } // pre : filename is the name of a legal GraphViz file of friendship connections // post: returns a map that contains for each person, the set of friends for that person public static Map> readFile(String filename) throws FileNotFoundException { Scanner input = new Scanner(new File(filename)); 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(); addFriend(friends, name1, name2); addFriend(friends, name2, name1); } } return friends; } // post: records a frienship for name1 and name2. If name1 is not in the map, // a set is added to the map containing name2. public static void addFriend(Map> friends, String name1, String name2) { /* Hunter: More verbose way to handle this * if (!friends.containsKey(name1)) { * Set theFriends = new TreeSet(); * theFriends.add(name2); * friends.put(name1, theFriends); * } else { * Set theFriends = friends.get(name1); * theFriends.add(name2); * // Why isn't this necessary? * // friends.put(name1, theFriends); * } */ if (!friends.containsKey(name1)) { friends.put(name1, new TreeSet()); } Set theFriends = friends.get(name1); theFriends.add(name2); } // post: computes the distance between two people, printing out // the set of friends that are certain "degrees" away from name1 public static void findFriends(Map> friends, String name1, String name2) { int distance = 0; Set currGroup = new TreeSet(); Set visited = new HashSet(); currGroup.add(name1); while (!currGroup.contains(name2) && !currGroup.isEmpty()) { // make sure we don't visit someone we've already visisted visited.addAll(currGroup); // find next group Set nextGroup = new TreeSet(); for (String name : currGroup) { nextGroup.addAll(friends.get(name)); } nextGroup.removeAll(visited); // update curr group and other info currGroup = nextGroup; distance++; System.out.println(" " + distance + " away: " + currGroup); } System.out.println("found at distance of " + distance); } }