Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement the following method. In this lab, a binary relation is represented us

ID: 3607105 • Letter: I

Question

Implement the following method.

In this lab, a binary relation is represented using a boolean matrix (double array of booleans) as follows.

Recall that A={a1,…an} and RA×A is a relation on A.

We represent a binary relation R using a matrix MR, where MR[i][j]=true means that (ai+1,aj+1)R, and MR[i][j]=false means that (ai+1,aj+1)R. (Note there is an “off by one” thing going on here. Our set starts couning elements at 1 but double arrays in Java are indexed starting at 0.)

public class Relations { /** * Returns composition of R and S. Return relation T such that if (i, j) in R and (j, k) in S then (i, k) in T. * @param S relation, represented as a matrix (double array) * @param R relation, represented as a matrix (double array) * @return S composed with R */ public static boolean[][] compose(boolean[][] R, boolean[][] S) { // compare matrix sizes and make sure they agree: if R is n1 x n2 then S should be n2 x n3. int n1 = R.length; int n3 = S.length; if (n1 == 0 || n3 == 0) throw new UnsupportedOperationException("expecting non-empty arrays!"); int n2 = R[0].length; int n4 = S[0].length; if (n2 == 0 || n4 == 0) throw new UnsupportedOperationException("expecting non-empty arrays!"); if (n2 != n3) throw new UnsupportedOperationException("Number of columns of R must match number of rows of S"); throw new UnsupportedOperationException("implement me!"); }

Explanation / Answer

public class Relations {

public static boolean[][] compose(boolean[][] R,boolean[][] S)

{

// compare matrix sizes and make sure they agree: if R is n1 x n2 then S should be n2 x n3.

int n1 = R.length;

int n3 = S.length;

if (n1 == 0 || n3 == 0) throw new UnsupportedOperationException("expecting non-empty arrays!");

int n2 = R[0].length;

int n4 = S[0].length;

if (n2 == 0 || n4 == 0) throw new UnsupportedOperationException("expecting non-empty arrays!");

if (n2 != n3) throw new UnsupportedOperationException("Number of columns of R must match number of rows of S");

boolean[][] T=new boolean[n1][n4];

for(int i=0;i<n1;i++)

for(int j=0;j<n4;j++)

T[i][j]=false;

for(int i=0;i<n1;i++)

{

for(int j=0;j<n2;j++)

{

for(int k=0;k<n4;k++)

if(R[i][j]&&S[j][k])

T[i][k]=true;

}

}

return T;

}

public static void main(String[] args)

{

boolean[][] A= {{true,true},{true,true},{false,false}};

boolean[][] B= {{true,true},{true,true}};

boolean[][] C=Relations.compose(A, B);

for(int i=0;i<C.length;i++)

{

for(int j=0;j<C[0].length;j++)

System.out.print(C[i][j]+" ");

System.out.println();

}

}

}

The output is

true true
true true
false false

Please give a thumbs up as it matters a lot and leave a comment in case there are doubts.