This question is for a program I am trying to write which involves connecting chains of physical parts together. I believe I have distilled it down into the simplest form of the question. I would also appreciate if someone knows any additional words that describe this problem, as about 30 min of searching for related questions hasn’t even turned up a name for this problem.
You have N vectors. If you choose one value from each vector and do not allow any repeats, you will have one permutation of the type I am trying to find. What is a pseudo-code algorithm to find all of them without brute forcing?
Example:
You have the vectors
v1=[1 2] v2=[1 2 3] v3=[1 2 3 4]
(Edit note: The nesting of the vectors is unintentional and cannot be leveraged in the algorithm.)
You pick values from each of the vectors and don’t allow repeats.
Value 1 is from v1 ---> 2
Value 2 is from v2 ---> 1
Value 3 is from v3 ---> 4
Resulting permutation is [2 1 4].
This is one allowable permutation. Here is an example of a permutation that is not allowed because it repeats.
Value 1 is from v1 ---> 2
Value 2 is from v2 ---> 1
Value 3 is from v3 ---> 2
Resulting permutation is [2 1 2], which is invalid due to repeats.
What is an algorithm to find all valid permutations?
Bonus points if you can calculate how many permutations there are before calculating them.
I’ll be sure to post back if I can come up with an answer before anyone else can.
The example you give has nested vectors, meaning that the entries in
v_iare a subset of those inv_{i+1}. If this is indeed the general case for your application, then the number of solutions is simply:where
n_iis the length ofv_iand there areknested vectors.As far as algorithms are concerned, if you want to generate all possible solutions, then I cannot see a better way than to choose from each successive vector after eliminating already selected entries.
If you aren’t nested, a good way to visualize this problem is as a Marriage Problem in the following sense. Make
kvertices corresponding to the givenkvectorsand another
mvertices corresponding to the distinct entries of the combined vectorsThen connect
a_itov_jif and only ifa_iappears inv_j. The goal is to find a maximum matching between thevs and theas that touches all of thev‘s. That is, choosekedges so that eachv_iis an endpoint of exactly one edge.Any of the standard algorithms, e.g. using augmented paths, will work to find one solution or generate them all.