import java.io.*; import java.util.*; public class Friends { public static void main(String[] args) throws FileNotFoundException { System.out.println("Welcome to the cse143 friend finder."); Scanner input = new Scanner(new File("friends.dot")); Map> friendNetwork = readFile(input); Scanner console = new Scanner(System.in); System.out.print("starting name? "); String name1 = console.next(); if (!friendNetwork.containsKey(name1)) { System.out.println("That person is not in the data file."); } else { System.out.print("target name? "); String name2 = console.next(); showMatches(friendNetwork, name1, name2); } } // pre : input is open and contains a legal Graphviz file of friendship // connections where each friend is listed as a single token // post: returns a map that contains for each person the set of friends for // that person public static Map> readFile(Scanner input) { Map> friendNetwork = new TreeMap>(); while (input.hasNextLine()) { String line = input.nextLine(); if (line.contains("--")) { Scanner lineData = new Scanner(line); String name1 = lineData.next(); lineData.next(); // this skips the "--" token String name2 = lineData.next(); // Add a friendship between name1 and name2 to our map // ex: name1 = Raymond // name2 = Anju updateMap(friendNetwork, name1, name2); updateMap(friendNetwork, name2, name1); } } return friendNetwork; } // post: records a friendship with name2 for name1 public static void updateMap(Map> friendNetwork, String name1, String name2) { /* if (!friendNetwork.containsKey(name1)) { // first time we've seen a key Set friendGroup = new TreeSet<>(); friendGroup.add(name2); friendNetwork.put(name1, friendGroup); } else { // we've seen this key already Set friendGroup = friendNetwork.get(name1); friendGroup.add(name2); // We don't need to put the set back in the map! // The map stores a reference to the set, so the updates // are already there }*/ if (!friendNetwork.containsKey(name1)) { friendNetwork.put(name1, new TreeSet<>()); } friendNetwork.get(name1).add(name2); } // post: computes the distance between two people, printing the various // lists of friends with their distance from name1 public static void showMatches(Map> friendNetwork, String name1, String name2) { // Meta: The algorithm here is much more complicated than what I'd // expect you to come up with on your own // The important part is how we're using sets and maps. Set currGroup = new TreeSet<>(); currGroup.add(name1); int distance = 0; Set visited = new HashSet<>(); while (!currGroup.isEmpty() && !currGroup.contains(name2)) { visited.addAll(currGroup); Set friendsOfCurrGroup = new TreeSet<>(); for (String curr : currGroup) { Set friendsOfCurr = friendNetwork.get(curr); for (String friend : friendsOfCurr) { if (!visited.contains(friend)) { friendsOfCurrGroup.add(friend); } } } currGroup = friendsOfCurrGroup; distance += 1; System.out.println(" " + distance + " away: " + currGroup); } } }