How to determine the set is transitive using java code?
import java.util.LinkedList;
public class Main {
public static boolean isTransitive(LinkedList<int[]> relations) {
for (int[] relationA : relations) {
for (int[] relationB : relations) {
if (relationA[1] == relationB[0]) {
boolean transitive = false;
for (int[] relationC : relations) {
if (relationC[0] == relationA[0] && relationC[1] == relationB[1]) {
transitive = true;
break;
}
}
if (!transitive) {
return false;
}
}
}
}
return true;
}
public static void main(String[] args) {
LinkedList<int[]> relations = new LinkedList<>();
relations.add(new int[]{2,1});
relations.add(new int[]{3,1});
relations.add(new int[]{3,2});
relations.add(new int[]{4,1});
relations.add(new int[]{4,2});
relations.add(new int[]{4,3});
System.out.println(isTransitive(relations));
relations = new LinkedList<>();
relations.add(new int[]{1,1});
relations.add(new int[]{1,2});
relations.add(new int[]{2,1});
relations.add(new int[]{2,2});
relations.add(new int[]{3,4});
relations.add(new int[]{4,1});
relations.add(new int[]{4,4});
System.out.println(isTransitive(relations));
}
}
Comments
Leave a comment