JSFiddle - React, Tailwind, and code Playground
by SpacePineapple
JavaScript
var A = [ 1,2,3,4,5 ];
var R = [ [1,2][1,3][2,3][5,6] ] ;
function isReflexive(R, A){
for(var i=0; i<A.length; i++)
if(!appliesRelation(R, [A[i], A[i]]))
return false;
return true;
}
function isTransitive(R, A){
for(var i=0; i<R.length; i++)
for(var j=0; j<R.length; j++)
if(R[i][1] == R[j][0] && !appliesRelation(R))
return false;
return true;
}
function isSymmetric(R, A){
for(var i=0; i<R.length; i++)
if(!appliesRelation(R, [R[i][1], R[i][0]]))
return false;
return true;
}
function partition(A, R){
if(!isTransitive(R) || !isReflexive(R, A) || !isSymmetric(R))
throw new Exception("only an equivalence relation partitions a set")
var partitions = [];
for(var i=0; i<A.length; i++){
var foundPartition = false;
for(var partitionIndex=0; partitionIndex < partitions.length && !foundPartition; partitionIndex++){
var p = partitions[partitionIndex];
if($.inArray(p, A[i]))
foundPartition = true;
for(var j=0; j<p.length && !partitionIndex; j++)
if(appliesRelation(R, [A[i][0], p[0]]) || appliesRelation(R, [A[i][0], p[1]]) ||
appliesRelation(R, [A[i][1], p[0]]) || appliesRelation(R, [A[i][1], p[1]]) ){
foundPartition = true;
p.push(A[i]);
}
}
}
}
function appliesRelation(R, couple){
return $.inArray(R, couple);
}