Vogel612 is pretty much right. The basic algorithm is: complete the equality relation, then test each inequality in the list to see if any conflicts. However, you would not generally do any completion on the inequalities.
I’ll mention that equivalence is transitive (a = b = c implies a = c) but inequality is not (1 ≠ 1+1 and 2 ≠ 1, but 1+1 = 2). Both are symmetric, though (if a = b, b = a), and equivalence is also reflexive (each element must equal itself).
The exact data structure to use might depend on whether we have a list of all the elements in advance, how many there are, and how sparse the truth table for the relation is likely to be. If the amount of memory we need to store the truth table as a two-dimensional array is reasonable, we could do it that way. Vogel612’s approach of storing the table as a collection of rows, each row containing the set of elements equivalent to its index, is a good way of storing a truth table with only a few elements equivalent to every element. (If every row is guaranteed to contain at least one element, itself, this should become an array or arrayList
.) Another approach is to create an arbitrary total ordering on the element names, such as the order in which we added them to an arrayList
, the hash value of their names, or a lexicographic ordering. This order has nothing to do with the values of those elements or the provided equality relation, but can be used to put every pair into a canonical form. That is, our elements are listed a, b, c, and a < b < c when we compare their names even if the values are equal by the relation. Keep a set (probably a hashSet
in Java) of tuples of elements (a,b) such that 'a' precedes 'b' in this ordering and their contents are equal, letting the facts that a = a, b = b and b = a be implicit. This will be efficient when very few other pairs of elements are equivalent. There are also more complicated data structures for sparse matrix storage that are not in the standard library.
In any case, you always want x ≠ x to fail and to look for the tuples in the same canonical form that you stored them in.