I have two arrays like below: A from 1 to 4 repeated 8 times, B from 1 to 8 repeated 4 times. I want to shuffle B but with one correlation condition on the final Matrix. I don't want the same B value (lets say 1 1 1 1) to appear in front of more than 3 different A values. To explain this better:
A: 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
B: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8
Acceptable shuffle
A: 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
B_shuffled: 8 8 8 8 2 3 2 1 2 1 5 6 4 3 7 1 7 1 7 2 7 5 5 4 6 5 6 6 3 4 3 4
Unacceptable shuffle (because 8 in B appeared in front of A: 1, 2, 3, 4 (more than three times)
A: 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
B_shuffled: 8 5 7 6 2 3 2 1 2 1 5 8 4 3 7 1 7 1 8 2 7 5 5 4 6 8 6 6 3 4 3 4
import numpy as np
A = np.arange(1, 4 + 1,1).tolist()
A = np.repeat(np.array(A[::1]), 8).tolist()
B = np.arange(1, 8 + 1,1).tolist()
B = np.repeat(np.array(B[::1]), 4).tolist()
I used random.shuffle(B) but couldn't figure out how to add distribution logic to it.
You can't add any type of distribution logic to
np.random.shuffleand even if you could, your constraints aren't really suited to it. We're not stuck though. Instead of using a one-liner we can procedurally build up a shuffled array that satisfies your requirements.Note that there's nothing
numpy-specific in this solution and unless you're using it surrounding code you can easily replace thenp.*functionality with vanilla Python.