-2

I have an array of integers of length 20, filled with fourteen 0s, two 1s, two 2s and two 3s. It is like this: [0,0,0,3,0,2,0,0,3,0,0,0,1,0,2,0,0,1,0,0].

I need a way to list all of its 20!/(14! 2! 2! 2!) permutations, without repetitions. (Note that in the list there are duplicate elements!)

I'm just looking for the right idea, it isn't necessary that you write the code. But, if you prefer writing the code, I only understand C and Java. Thanks :)

Matteo
  • 119

1 Answers1

0

I borrowed algorithm from https://stackoverflow.com/questions/2710713/algorithm-to-generate-all-possible-permutations-of-a-list and made a simple change to it so it ignores same elements when swapping them.

def permute(xs, low=0):
    if low + 1 >= len(xs):
        yield xs
    else:
        for p in permute(xs, low + 1):
            yield p        
        for i in range(low + 1, len(xs)):        
            if xs[low] == xs[i]:
                continue
            xs[low], xs[i] = xs[i], xs[low]
            for p in permute(xs, low + 1):
                yield p        
            xs[low], xs[i] = xs[i], xs[low]

for p in permute([0, 1, 0, 2, 0, 3]):
    print(p)
Euphoric
  • 37,384