Generating all unique orders of looping series of characters (all circular permutations)

笑着哭i 提交于 2019-12-11 18:23:39

问题


  • I have a string that is made out of Xs and Ys.

For the sake of the question let's say this string is constructed of Four-Xs and Two-Ys:

XXYYYY

How can I generate all of the possible unique strings that are made out of Four-Xs and Two-Ys given that the string is not considered unique if by looping (/rotating/shifting) its characters around it produces a string that was already found?

For instance:

XXYYYY is considered similar to YXXYYY and YYYXXY (cardinal numbers added clarify)
123456                          612345     456123

Notice: that the order of the characters stays unchanged, the only thing that changed is the starting character (The original string starts with 1, the 2nd string with 6, and the 3rd with 4, but they all keep the order).

In the case of Two-Xs and Four-Ys (our example) all the possible permutations that are unique are:

XXYYYY
XYXYYY
XYYXYY

And every other order would be a shifted version of one of those 3.

How would you generate all of the possible permutation of a string with and N number of Xs and an M number of Ys?


回答1:


Essentially you need to generate combinatorial objects named binary necklaces with fixed number of ones

This is Python code adapted from Sawada article "A fast algorithm to generate necklaces with fixed contents".
(I used the simplest variant, there are also more optimized ones)

n = 6
d = 3
aa = [0] * n
bb = [n - d, d]  #n-d zeros, d ones

def SimpleFix(t, p):
    if t > n:
        if n % p == 0:
            print(aa)
    else:
        for j in range(aa[t - p - 1], 2):
            if bb[j] > 0:
                aa[t - 1] = j
                bb[j] -= 1
                if j == aa[t-p-1]:
                    SimpleFix(t+1, p)
                else:
                    SimpleFix(t+1, t)
                bb[j] += 1

SimpleFix(1, 1)

#example for 3+3

[0, 0, 0, 1, 1, 1]
[0, 0, 1, 0, 1, 1]
[0, 0, 1, 1, 0, 1]
[0, 1, 0, 1, 0, 1]


来源:https://stackoverflow.com/questions/55015313/generating-all-unique-orders-of-looping-series-of-characters-all-circular-permu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!