import java.util.*; import java.io.*; /** * This class does a "degrees of separation" analysis on the given input file. * small-twitter.dot consists of twitter communications. The goal is given * two people A and B, find the distance apart those two people are via * twitter communications. * * @author Adam Blank */ public class Twitter { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("small-twitter.dot")); // key: a user (String) // value: another map? anyone connected // who is one away from this user? // set of all people one away Map> twitterCommunications = new HashMap<>(); 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(); // name1 -- name2 // key value addToMap(twitterCommunications, name1, name2); addToMap(twitterCommunications, name2, name1); } } findDistance(twitterCommunications); } public static void addToMap(Map> twitterCommunications, String name1, String name2) { if (!twitterCommunications.containsKey(name1)) { twitterCommunications.put(name1, new HashSet()); } // add name2 to the set mapped to by name1 twitterCommunications.get(name1).add(name2); } public static void findDistance(Map> twitterCommunications) { Scanner console = new Scanner(System.in); System.out.print("First person? "); String name1 = console.next(); System.out.print("Second person? "); String name2 = console.next(); /* Current is the "frontier" that we are exploring. The people in this * set are our current distance away from the starting person. */ Set current = new HashSet<>(); /* When we begin, name1 is the only person of zero distance away from * name1. */ current.add(name1); int distance = 0; while (!current.contains(name2)) { distance++; // Every time through this loop, we add people of // distance one further from name1. /* Collect all of the people of distance 1 from the people we * are currently looking at. */ Set next = new HashSet<>(); for (String person: current) { next.addAll(twitterCommunications.get(person)); } /* Now that we've added everyone we've seen to our "next" set, * those people are the next distance we need to check. */ current = next; } System.out.println(name1 + " is " + distance + " away from " + name2); } }