//Program 1b
//Professor Pattis, ICS-23 Lab 1
//Programmers: Cameron Ruatta, Derek Elder
import edu.uci.ics.pattis.introlib.Prompt;
import edu.uci.ics.pattis.introlib.TypedBufferReader;
import edu.uci.ics.pattis.ics23.collections.*;
import java.util.StringTokenizer;
import java.io.EOFException;
import java.util.Arrays;
public class Reverse
{
public static void printGraph(Map<String,Set<String>> graphMap, String output)
{
System.out.println(output);
List<String> sourceNodesList = new ArrayList<String>(graphMap.keys());
Collections.sort(sourceNodesList);
for(String sourceNode : sourceNodesList)
{
Set<String> destinationNodes = graphMap.get(sourceNode);
System.out.println(sourceNode + " -> " + destinationNodes);
}
}
public static Map<String,Set<String>> reverse(Map<String,Set<String>> graphMap)
{
Map<String,Set<String>> reverseMap = new ArrayMap<String,Set<String>>();
for(String newValue : graphMap.keys()) //Go through old keys (new values)
{
for(String newKey : graphMap.get(newValue)) //Go through old values (new keys)
{
Set<String> nodes = reverseMap.get(newKey);
if (nodes == null)
{
nodes = new ArraySet<String>();
reverseMap.put(newKey,nodes);
}
nodes.add(newValue);
}
}
return reverseMap;
}
public static void main(String[] args)
{
Map<String,Set<String>> graphMap = new ArrayMap<String,Set<String>>();
TypedBufferReader tbr = new TypedBufferReader("Enter name of file with graph");
//Repeatedly read lines from a file until the EOFException is thrown.
for (;;)
{
try
{
String line = tbr.readLine();
StringTokenizer st = new StringTokenizer(line, ";");
String sourceNode = st.nextToken();
while (st.hasMoreTokens())
{
String token = st.nextToken();
//Update map for the current node
Set<String> nodes = graphMap.get(sourceNode);
if (nodes == null)
{
nodes = new ArraySet<String>();
graphMap.put(sourceNode,nodes);
}
nodes.add(token);
}
} catch (EOFException e) {break;}
}
printGraph(graphMap, "Graph: source -> {destination} edges");
printGraph(reverse(graphMap), "Reverse Graph: source -> {destination} edges");
}
}