【问题标题】:get the i-th combination of arrays of numbers获得数字数组的第 i 个组合
【发布时间】:2013-05-28 06:54:42
【问题描述】:

我知道有很多类似的问题,而且我已经阅读了好几个小时。但似乎没有一个符合我的要求。

我的问题:

给定 n 个 int 数组,每个数组的格式为

array_i[] = {0, 1,...,count_i-1}, i = 0,1,...,n-1.

我们在每个数组中选择一个数进行组合,这样的组合数为

count_0*count_1*...*count_{n-1}

例如

array_0 = {0,1}
array_1 = {0,1,2}
array_2 = {0,1}

2*3*2 = 12 个组合是

 0| 0 0 0
 1| 0 0 1
 2| 0 1 0
 3| 0 1 1
 4| 0 2 0
 5| 0 2 1
 6| 1 0 0 
 7| 1 0 1
 8| 1 1 0
 9| 1 1 1
10| 1 2 0
11| 1 2 1

我想获得第 i 个组合(例如第 9 个组合是{1,1,1})并有效地获得它。我已经尝试过 base-n 转换的想法,类似于 Permutation for numbers in C。但它效率不高,因为基数必须是最大的count_i,这可能是不必要的。我还考虑过为每个位使用不同的基数的想法,但是要正确地建立关系是很棘手的。

真的欢迎任何建议。

【问题讨论】:

    标签: c algorithm permutation combinations


    【解决方案1】:

    与您的链接 (Permutation for numbers in C) 的主要区别在于 49^i 成为 count_j 的乘积:

    index_0 = ( i / sub_0 ) % count_0
    index_1 = ( i / sub_1 ) % count_1
    ...
    

    你预先计算的地方

    sub_0 = count_1*count_2*...*count_{n-1}
    sub_1 = count_2*count_3*...*count_{n-1}
    ...
    

    在计数 = 2,3,2 的示例中,我们有 sub=6,2,1,因此对于 i=9 索引=1,1,1

    【讨论】:

    • 但是将您的方法应用到我的示例中,prod_0 = 2, prod_1 = 1,第 9 个组合的索引是 index_0 = 9%2 = 1, 9%1 = 0?跨度>
    • 重新定义您的数组以从 0 运行到 count-1;否则你对组合总数的表达是错误的。那么count_i 就变成了array_i 中的元素个数。然后在您的示例中计数为 2,3,2。
    • 是的,你是对的。但是现在 prod_0 = 6, prod_1 = 2,第 9 个组合的索引是 index_0 = 9%6 = 3, 9%2 = 1?
    • 谢谢。真的很整洁。
    猜你喜欢
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多