arraysalgorithmmathpermutation

Finding all possible bijections between two sets


I want to create an algorithm, able to find all the possible bijections between two sets of objects.

A simple example, let's suppose we have two arrays {1,2,3}, {4,5,6}.

The algorithm should give me 3! = 3×2×1 = 6 bijections which are the following:

1-4, 2-5, 3-6
1-4, 2-6, 3-5
1-5, 2-4, 3-6
1-5, 2-6, 3-4
1-6, 2-5, 3-4
1-6, 2-4, 3-5

Even though it seems simple at first place, I am quite stuck. Is there any standard algorithm in the theory of combinatorics, bijections or permutations to solve this problem?


Solution

  • You should do it recursively, "choose" one variable from each - and add it to the solution - do it for all possibilities, and narrow your possible choices at each recursive call.

    Pseudo code should be something like [assuming |S1| == |S2|]:

    getAllBijections(S1,S2,sol):
       if (S1 is empty):
           print sol
       else:
           first <- S1.first
           S1 <- S1.deleteFirst()
           for each e in S2:
               S2.remove(e)
               sol.append(first,e)
               getAllBijections(S1,S2,sol) // note we are invoking with modified S1,S2,sol
               sol.removeLast() //remove the last sol
               S2.add(e) //return e to S2
           end for
       end if
    

    Note that it indeed generate n! possibilities, because for each iteration you have one less element to choose from, resulting in total of n * (n-1) * ... * 1 = n! possibilities, as expected..