In: Computer Science
A JAVA program that will read a boolean matrix corresponding to a relation R and output whether R is Reflexive, Symmetric, Anti-Symmetric and/or Transitive.
Input to the program will be the size n of an n x n boolean matrix followed by the matrix elements. Document your program nicely.
NOTE: The program must output a reason in the case that an input relation fails to have a certain property.
public class BooleanMatrix {
// read matrix from standard input
public static boolean[][] read() {
int n = StdIn.readInt();
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (StdIn.readInt() != 0) a[i][j] = true;
}
}
return a;
}
// print matrix to standard output
public static void print(boolean[][] a) {
int n = a.length;
StdOut.println(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j]) StdOut.print("1 ");
else StdOut.print("0 ");
}
StdOut.println();
}
}
// random n-by-n matrix, where each entry is true with
probability p
public static boolean[][] random(int n, double p) {
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = StdRandom.bernoulli(p);
}
}
return a;
}
// display the matrix using standard draw
// depending on variable which, plot true or false entries in
foreground color
public static void show(boolean[][] a, boolean which) {
int n = a.length;
StdDraw.setXscale(0, n-1);
StdDraw.setYscale(0, n-1);
double r = 0.5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] == which) {
StdDraw.filledSquare(j, n-i-1, r);
}
}
}
}
// test client
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
double p = Double.parseDouble(args[1]);
boolean[][] a = random(n, p);
print(a);
show(a, true);
}
}