Amitabh
BAN USERpackage inhouse.project;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
public class FriendsAssociation {
public static void main(String[] args) {
File f = new File("c:\\Users\\amitabh\\Desktop\\friends.txt");
//calling method for calculating association
printFriendsByAssociationLevel(f,"A");
}
public static void printFriendsByAssociationLevel(File f, String friend){
if(f==null){
System.out.println("Unable to read");
}
else{
Map<String, String[]> fmap = new HashMap<String,String[]>();
Scanner scanHandle = null;
try {
scanHandle = new Scanner(f);
while(scanHandle.hasNext()){
String s = scanHandle.nextLine();
String[] kv = s.split(":");
String key = kv[0];
String[] values = kv[1].split(",");
fmap.put(key, values);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int level = 1;
boolean needComma = false;
Set<String> hasPrinted = new HashSet<String>();
hasPrinted.add(friend);
Queue<String> q1 = new LinkedList<String>();
Queue<String> q2 = new LinkedList<String>();
Queue<String> temp = new LinkedList<String>();
pushToQueue(q1,fmap.get(friend),hasPrinted);
System.out.println("Level:"+ level);
while(!q1.isEmpty()){
String aFriend = q1.remove();
if(!hasPrinted.contains(aFriend)){
if(!needComma){
System.out.print(aFriend);
needComma = true;
}
else{
System.out.print(","+aFriend);
}
pushToQueue(q2, fmap.get(aFriend),hasPrinted);
hasPrinted.add(aFriend);
}
if(q1.isEmpty()){
level++;
temp = q1;
q1 = q2;
q2 = temp;
needComma = false;
System.out.println();
if(!q1.isEmpty()){
System.out.println("Level:"+ level);
}
}
}
}
}
public static void pushToQueue(Queue<String> q,String[] s, Set<String> has){
if(s!=null){
for(int var = 0; var < s.length; var++ ){
if(!has.contains(s[var])){
q.add(s[var]);
}
}
}
}
}
Hi Mike,
- Amitabh June 24, 2015Your code will not produce the output in the format as per the question. you have kept the printing of "level" inside the while loop. So, for each item in the queue , it will print "Level" in a new line. Also, you need to swap q1 and q2. not just q1 = q2. And, you have not considered the extreme case like, what happens if a friend name appears on the left as well as on the right, like:
A:B,C,D
D:X,A
it may result in an endless loop.
I have also submitted the answer. Please check and comment.