I have a list of formulae for combining elements:
A + B + C = X
D + E + F = Y
G + H + I = Z
I want to ensure that given any random 4 elements, there will never be more than 1 applicable formula. For example the formulae below should not be allowed as if I get elements A, B, C and D then both are applicable:
A + B + C = X
B + C + D = Y
Every formula will consist of 3 elements on the LHS and it’s the LHS that I want to enforce the rule on.
The elements are sortable, if that helps.
An alternative, equivalent problem:
I have a list of an array of 3 elements: List<Element[3]> How do I ensure that no 2 elements appear in more than one array.
What would be a reasonably efficient (runtime speed) way of doing this for a large number of elements and a large number for formulae (beyond brute forcing)?
You can represent the constraints on the set of equations as a graph. The vertices are the elements, with
n[i]elements in equationi. For equationi, there are thusn[i]*(n[i]-1)/2pairs of elements; these become edges. Iterate through the equations, adding the edges to the graph. Anytime you’d want to add an edge that is already present, you’ve found a conflict.For each edge, you could store a set of equation numbers that would generate the edge; this allows the specific conflicts to be identified, rather than just the presence of conflicts.
Let
Nbe the number of equations andMthe number of elements in the equation with the most elements. The time complexity isO(M^2*N), as is the space complexity. If all equations have a fixed number of elements, time and space usage will thus beO(N).