JAVA Counting Friendship Pairs Write a program that creates a 2D array of 5x5 va
ID: 3706037 • Letter: J
Question
JAVA
Counting Friendship Pairs
Write a program that 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. Use initializer list to instatiate and initialize your array to represent the following configuration:
Write some code 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).
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. Make this method static and test it from the main() method.
Notes:
Every question must be in a different class ( you should have 3 classes)
Use methods in your code (don’t write all your code in main method)
2 (* means "friends")Explanation / Answer
public class friendship {
public static void main(String[] args) { //main function
char array[][] = new char[5][5]; // array initialisation
array[0][1]=array[1][0]=array[0][3]=array[3][0]=array[0][4]=array[4][0]='*';
array[1][2]=array[2][1]=array[1][4]=array[4][1]='*';
array[3][4]=array[4][3]='*';
friends(array); // function call to print total no. of distinct pairs
checks(array,1,3); // functio to check common friends
}
public static void friends(char array[][]) {
int i,j,count=0;
for(i=0;i<5;i++)
for(j=0;j<i;j++)
if(array[i][j]=='*')
count++;
System.out.println("Total pair of friends = " +count);
}
public static void checks(char array[][], int i, int j) {
int k, flag=1;
for(k=0;k<5;k++)
if(array[i][k]=='*' && array[j][k]=='*')
{
System.out.println("Yes! " +i + " and " +j + " have common friend and that is: " +k);
flag=0;
break; // after getting 1st common friend break the loop
}
if(flag==1)
System.out.println("No! " +i + " and " +j + " don't have common friends.");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.