生成所有可能的分裂

时间:2016-01-23 22:04:19

标签: algorithm combinations combinatorics

我正在寻找以下任务中最快的算法。我有一些数组

[a,b,c ...]

我需要生成一些同样随机的数组数组,其中包含主数组的所有元素,如下所示:

Input [1 2 3 4 5 ] => [ [1 2 ] [3 4 ] [ 5 ] ]

Straitforward解决方案是生成所有拆分并随机选择其中一个。该解决方案保证将以相同的概率选择所有分裂。但它对于大数字来说太慢了。还有其他可能来创建这种分裂吗?

1 个答案:

答案 0 :(得分:2)

对于每个可能的分裂点,随机决定是否在那里分裂。例如,在Python中:

import random

def random_split(input_list):
    result = [[]]

    # Assume input is nonempty, since it's not clear what the result should
    # be if the input is empty.
    result[-1].append(input_list[0])

    for item in input_list[1:]:
        if random.randrange(2):
            # Split here.
            result.append([])
        result[-1].append(item)

    return result