Arrangement of array elements - equal distribution of sequences

Suppose I have a numpy shuffled array:

a = np.array([1,2,3,4,5,6]*6)
np.random.shuffle(a)

How can I guarantee that every element in a shuffled array follows every other element an equal number of times?

For example, I want to make sure that number 1 follows number 2 in the array as many times as it follows number 4. Similarly, for all other numbers

We can assume that the list is round for this problem, i.e. the first element follows the last

Normally I would post the code of what I tried, but I don't understand when it comes to this.

The most inefficient way I can think of is to write a function that counts how many times a number follows another number, and then check that all the counts are equal. If not, rearrange.

But this does not guarantee that I have ever completed a list that meets the criteria for equal distribution.

+4
source share
1 answer

Here is the best I can think of. Please note that with 36 numbers, each number must follow the number once.

while True:
    x = {i: set(range(1,7)) for i in range(1,7)}

    a = [random.choice(range(1,7))]  # start with a random number
    last = a[-1]
    while x[last]:
        next = random.choice(list(x[last]))
        x[last].remove(next)
        a.append(next)
        last = next

    if len(a) == 37:
        # We get to length 37 if and only if each set above is exhausted.
        # In this case, the first item will always equal the last item
        # (proof left as an exercise for the reader), so remove it.
        a = a[:-1]
        break

print(''.join(str(i) for i in a))

which produces for me 221164425231355145433465615366263241, which, apparently, meets the criteria.

+3
source

Source: https://habr.com/ru/post/1612662/


All Articles