Suppose that we are given arrays A
and B
of positive integers. A
and B
contain the same integers (the same number of times), so they are naturally the same length.
Consider permutations of two arrays U
and V
to be valid if U[i] != V[i]
for i = 0, 1, ..., len(U) - 1
.
We want to find a valid pair of permutations for A
and B
. However, we want our algorithm to be such that all pairs of valid permutations are equally likely to be returned.
I've been working on this problem today and cannot seem to come up with a sleek solution. Here is my best solution thus far:
import random
def random_valid_permutation(values):
A = values[:]
B = values[:]
while not is_valid_permutation(A, B):
random.shuffle(A)
random.shuffle(B)
return A, B
def is_valid_permutation(A, B):
return all([A[i] != B[i] for i in range(len(A))])
Unfortunately, since this method involves a random shuffle of each array, it could in theory take infinite time to produce a valid output. I have come up with a couple of alternatives that do run in finite (and reasonable) time, but their implementation is much longer.
Does anyone know of a sleek way to solve this problem?