满足给定约束的模式组合

时间:2018-07-26 04:12:22

标签: algorithm sorting combinations

给出了由1和0组成的模式。总是7位,3位是1s,4位是0s

示例-1100010

约束是一次考虑2个0,然后用1代替它们。我需要找到所有可能的组合。

到目前为止,我的想法是,找到0的索引并运行一个for循环以在每次运行时选择2个索引并获取输出。

示例-

给定模式-1100010

必需的输出-1111010、1110110、1110011、1101110、1101011、1100111

我可以详尽地做到这一点。任何以更优化的方式执行此操作的建议都将真正有用。

2 个答案:

答案 0 :(得分:0)

您的问题归结为找到4选择2的所有组合。获取零索引的想法是一个很好的起点。

对于给定的示例1100010,我们具有以下内容:

1 1 0 0 0 1 0
| | | | | | |
V V V V V V V 
0 1 2 3 4 5 6   // indices here assuming base 0

因此,我们零索引的向量为{2, 3, 4, 6}

现在,我们可以生成零索引向量选择2的所有组合(SO或Web上很容易找到几种出色的算法),并进行适当的替换以生成我们的输出。

伪代码:

inputVec = {1,1,0,0,0,1,0}
zeroIndex = {}

for i in 0 to (length(inputVec) - 1)
    if (inputVec[i] == 0)
        zeroIndex.push_back(i)     // zeroIndex = {2, 3, 4, 6} for the given example

// initialize output vector to the input vector
newOutput = inputVec
myCombos = generateCombos(zeroIndex, 2) // matrix of combinations with 2 columns

for i in 0 to (length(myCombos) - 1) {
    newOutput[myCombos[i, 0]] = 1
    newOutput[myCombos[i, 1]] = 1
    print(newOutput)

    // reset output vector
    newOutput = inputVec
}

在上述算法中,generateCombos将输出以下内容:

     [,0] [,1]
[0,]    2    3
[1,]    2    4
[2,]    2    6
[3,]    3    4
[4,]    3    6
[5,]    4    6

概述的算法适用于一般情况,即输入向量具有任何长度,并且具有任意数量的0和1。

答案 1 :(得分:0)

  1. 查找输入中四个零的位置并编号其位位置。
  2. 暂时忽略输入中零的位置,您有四个零,它们将变成两个零和两个1。
  3. 按顺序查找唯一的一组排列“ 0011”。
  4. 对于每个烫发:将1和0(保留顺序)替换为原始编号中零的原始位置,以产生其中一个输出。

类似的东西:

from itertools import permutations
from pprint import pprint as pp

unique_perms = set(permutations('0011'))

num = input('number: ').strip()  # Keep as text
for perm in unique_perms:
    out = []
    p = list(perm)
    for bit in num:
        out.append(bit if bit == '1' else p.pop())
    print('->', ''.join(out))

样品运行:

number: 1100010
-> 1111010
-> 1101110
-> 1110110
-> 1100111
-> 1110011
-> 1101011
相关问题