Getting permutations of independent sequences with uniform probability

permutationsrandomrandom walk

Let's say we have $n=3$ sequences noted $A, B, C$ each composed of $m=3$ ordered operations such that $A = (A_0, A_1, A_2)$, $B = (B_0, B_1, B_2)$ and $C = (C_0, C_1, C_2)$.

I am searching for an algorithm that returns a sequence of 9 operations with a random ordering but still preserving the order of each sequence (e.g. $(A_0, B_0, A_1, C_0, C_1, A_2, B_1, C_2, B_2)$). This gives exactly $\frac{(nm)!}{(m!)^n} = \frac{9!}{(3!)^3} = 1680$ possibles sequences.

The only solution I've found so far can be summarized by the following pseudo-code:
enter image description here

To put it in a nutshell, it randomly picks a sequence at each step and add its current operation to the output sequence.

However, a drawback of this method is that all output sequences do not occur with the same probability. For instance $(A_0, A_1, A_2, B_0, B_1, B_2, C_0, C_1, C_2)$ occurs with probability $\left(\frac{1}{3}\right)^3 \times \left(\frac{1}{2}\right)^3 = \frac{1}{216}$ while $(A_0, A_1, B_0, B_1, C_0, C_1, A_2, B_2, C_2)$ occurs with probability $\left(\frac{1}{3}\right)^7 \times \frac{1}{2} = \frac{1}{4374}$.

What kind of algorithm could I use to build output sequences that occur with a uniform probability (i.e. $\frac{1}{1680}$ in this specific toy example)?

Best Answer

Ignore the order constraint first and generate a random combined sequence of operations. Then for each of the $n$ individual sequences, keep the positions its $m$ operations occupy in the combined sequence, but sort those operations to satisfy the order constraint.

Each valid combined ordering is the result of sorting any one of $(m!)^n$ raw orderings, so the valid orderings have a uniform probability of being produced.