Write a java program to creates a 2D array of 5x5 values of type boolean. Suppos
ID: 3712597 • Letter: W
Question
Write a java program to creates a 2D array of 5x5 values of type boolean. Suppose indices represent people and that the value at row i, column j of a 2D array is true just in case i and j are friends and false otherwise.
1: Initialize your array to represent the following configuration:
2: Write a method to count how many pairs of friends are represented in the array.
Note that each friendship pair appears twice in the array, so in the example above there are 6 pairs of friends).
3: Write a method to check whether two people have a common friend.
For example, in the example above, 0 and 4 are both friends with 3 (so they have a common friend), whereas 1 and 2 have no common friends. The method should have three parameters: a 2D array of boolean representing the friendship relationships and two integers i, j. The method should return true if there is an integer k, such that i is a friend of k and k is a friend of j and return false otherwise.
#101234 (* means "friends" 0Explanation / Answer
class Friends{
boolean b[][];
public Friends()
{
int i,j;
b= new boolean[5][5];
for(i=0;i<5;i++)
for(j=0;j<5;j++)
b[i][j]=false;
}
public void initilizeArray()
{
b[0][1]=b[1][0]=true;
b[0][3]=b[3][0]=true;
b[0][4]=b[4][0]=true;
b[1][2]=b[2][1]=true;
b[1][4]=b[4][1]=true;
b[3][4]=b[4][3]=true;
}
public int countPair()
{
int count=0,i,j;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
if(b[i][j]==true)
count++;
return count/2;
}
public int commonFriends(int i, int j)
{
int k,count=0;
for(k=0;k<5;k++)
if(b[i][k]==b[j][k]&&(b[i][k]==true&&b[j][k]==true))
count++;
return count;
}
}
class Rextester{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Friends F=new Friends();
F.initilizeArray();
System.out.print(" Pair="+F.countPair());
System.out.print(" Common Friends:"+F.commonFriends(0, 3));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.