Please help with the code for this algorithm A “friend_to_all” in a social media
ID: 3887108 • Letter: P
Question
Please help with the code for this algorithm
A “friend_to_all” in a social media with n members is someone who does not know anybody else but who is known by all other members in the social media. The problem in a social media of n members is to identify a “friend_to_all”, if one exists. To find a “friend_to_all”, the only possible action is to ask a question to any member i: “Do you know member j?” The assumption is that everybody tells the truth. Design and implement an algorithm to find “friend_to_all” in a social media of n members.
i=1 j=1
while (j<=n) do if (“Does j know i?”) then j=j+1
else i=j and j=j+1
friend_to_all-FOUND=TRUE and j=1
while (j < i and friend_to_all-FOUND)do
if (“Does j know i?”) then j=j+1
else friend_to_all-FOUND= FALSE
k=1
while (k<=n and friend_to_all-FOUND) do
if (k!=i and “Does i know k?”) then friend_to_all-FOUND=FALSE
else k=k+1
if friend_to_all-FOUND then return “The friend_to_all is i.”
else return “There is no friend_to_all"
Explanation / Answer
import java.util.Scanner;
public class FriendToAll {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("Members in Social Media:");
int n=scn.nextInt();
int i=1,j=1,k=1;;
boolean friend_to_all=false;
int count=0;
while (j<=n)
{
System.out.println("Does j know i?");
String know=scn.next();
if (know.equalsIgnoreCase("Yes")) {
j=j+1;
count++;
}else {
i=j;
j=j+1;
}
System.out.println(count);
if(n==count){
friend_to_all=true;
}
}
if(friend_to_all==true && j==1)
while (j < i && friend_to_all)
{
System.out.println("Does j know i?");
String knows=scn.next();
if (knows.equalsIgnoreCase("Yes")) { j=j+1; }
else {
friend_to_all= false;
k=1;
}
}
while (k<=n && friend_to_all) {
System.out.println("Does i know k?");
String knowsK=scn.next();
if (k!=i && knowsK.equalsIgnoreCase("Yes")) { friend_to_all=false;
}
else{ k=k+1;}
if( friend_to_all){ System.out.println("The friend_to_all is i.");}
else System.out.println("There is no friend_to_all");
}
if( friend_to_all){ System.out.println("There is no friend_to_all.");}
}
}