For example, if A and B are friends and B and C are friends, then A.canBeConnected(c)
should return true since C is a friend of B and B is a friend of A.
while running the code I am getting an error:
Exception in thread "main" java.lang.UnsupportedOperationException: Waiting to be implemented.
at Friend.canBeconnected(Friend.java:35)
at Friend.main(Friend.java:48)
I tried below code
import java.util.Collection;
import java.util.ArrayList;
public class Friend {
private Collection<Friend> friends;
private String email;
public Friend(String email)
{
this.email = email;
this.friends = new ArrayList<Friend>();
}
public String getEmail()
{
return email;
}
public Collection<Friend> getFriends()
{
return friends;
}
public void addFriendship(Friend friend)
{
friends.add(friend);
friend.getFriends().add(this);
}
public boolean canBeconnected(Friend friend)
{
throw new UnsupportedOperationException("Waiting to be implemented.");
}
public static void main (String[] args)
{
Friend a = new Friend("A");
Friend b = new Friend("B");
Friend c = new Friend("C");
a.addFriendship(b);
b.addFriendship(c);
System.out.println(a.canBeconnected(c));
}
}
Please can someone help me to solve this.
You can use breadth first search to solve this problem. I have assumed that emails can be used to uniquely identify a friend.
Note that the following code requires importing java.util.Set
, java.util.HashSet
, java.util.Queue
, and java.util.ArrayDeque
.
public boolean canBeconnected(Friend friend){
final Set<String> vis = new HashSet<>();
final Queue<Friend> queue = new ArrayDeque<>();
queue.offer(this);
vis.add(this.email);
while(!queue.isEmpty()){
final Friend curr = queue.poll();
if(curr.email.equals(friend.email)) return true;
for(final Friend next: curr.friends)
if(vis.add(next.email))
queue.offer(next);
}
return false;
}
You could also use depth first search by calling the canBeconnected
method on each friend.
public boolean canBeconnected(Friend friend){
if(this.email.equals(friend.email)) return true;
for(final Friend next: this.friends)
if(next.canBeconnected(friend)) return true;
return false;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments