In: Computer Science
Write a program in java to determine whether a given function F from the set {0,1,2,3,...,m} to (0,1,2,3,...,n} is one-to-one and/or onto. The inputs to your program will be:
- an integer m
- an integer n, and
- a two dimensional boolean array F of size (m+1) x (n+1), where F[ i , j ] = 1 if F(i) = j.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main
{
public static boolean checkOneToOne(int m, int n, int F[][])
{
// check if every column has less than or equal to one 1.
for (int j = 0; j <= n; j++) {
int count_one = 0;
for (int i = 0; i <= m; i++) {
count_one += F[i][j];
}
if (count_one > 1)
return false;
}
return true;
}
public static boolean checkOnto(int m, int n, int F[][]) {
// check if every column has atleast one 1.
for (int j = 0; j <= n; j++) {
int count_one = 0;
for (int i = 0; i <= m; i++) {
count_one += F[i][j];
}
if (count_one == 0)
return false;
}
return true;
}
public static void main(String[] args) throws
IOException {
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter m:
");
int m =
Integer.parseInt(br.readLine());
System.out.print("Enter n:
");
int n =
Integer.parseInt(br.readLine());
int F[][] = new int[m + 1][n +
1];
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
System.out.print("Enter F[" + i +
", " + j +"]: ");
F[i][j] =
Integer.parseInt(br.readLine());
}
}
if (checkOneToOne(m, n, F))
System.out.println("Function is
one-to-one.");
else
System.out.println("Function is not
one-to-one.");
if (checkOnto(m, n, F))
System.out.println("Function is
onto.");
else
System.out.println("Function is not
onto.");
br.close();
}
}