问题
I have a set M which consists of three subsets A,B and C.
Problem: I would like to calculate all possible subsets S(1)...S(N) of M which contain all possible pairs between elements of A, B and C in such manner that:
- elements of A and B can happen in a pair only once for each of two positions in a pair (that is
{a1,a2}
and{b1,a1}
can be in one subset S, but no more elements{a1,_} and {_,a1}
are allowed in this subset S); - elements of C can happen 1-N times in a subset S (that is
{a,c}, {b,c}, {x,c}
can happen in one subset S), but I would like to get subsets S for all possible numbers of elements of C in a subset S.
For example, if we have A = [a1,a2], B = [b1,b2], C = [c1,c2]
, then some of the resulting subsets S would be (remember, they should contain pairs of elements):
- {a1,b1}, {b1,a2}, {a2,b2}, {b2,c1};
- {a1,b1}, {b1,a2}, {a2,b2}, {b2,c1}, {c1,c2};
- {a1,c1}, {c1,a2}, {c1,b2}, {b1,c1};
- etc.
I tend to think that first I need to find all possible subsets of M, which contain only one element of A, one element of B and 1..N elements of C (1)
. And after that I should somehow generate sets of pairs (2)
from that. But I am not sure that this is the right strategy.
So, the more elaborated question would be:
- what is the best way to create sets and find subsets in Erlang if the elements of the set M a integers?
- are there any ready-made tools to find subsets of a set in Erlang?
- are there any ready-made tools to generate all possible pairs of elements of a set in Erlang?
- How can I solve the aforementioned problem in Erlang?
回答1:
There is a sets module*, but I suspect you're better off thinking up an algorithm first -- its implementation in Erlang is the problem (or not) that comes after this. (Maybe you notice its actually a graph algorithm (like, bipartite matching something something), and you'll get happy with Erlang's digraph module.)
Long story short, when you come up with an algorithm, Erlang can very probably be used to implement it. Yes, there is a certain support for sets. But solutions to a problem requiring "all possible subsets" tend to be exponential (i.e., given n
elements, there are 2^n
subsets; for every element you either have it in your subset or not) and thus bad.
(* there are some modules concerning sets)
来源:https://stackoverflow.com/questions/7937930/how-to-find-all-possible-pairs-from-three-subsets-of-a-set-with-constraints-in-e