簡體   English   中英

無重復生成數字組合的算法

[英]algorithm for generating number combinations without repetition

我檢查了這里幾乎所有類似的帖子,但我不知道如何做我想做的事。 我正在嘗試的是在 C 程序中提供一個輸入,比如數字 4,程序返回數組中的以下數字:

1
2
3
4
12
13
14
23
24
34
123
134
124
1234

更清楚一點:如果輸入數字是 4,那么我想使用數字 1-4 並生成所有可能的數字組合(從 1 位組合到 4 位組合),沒有數字重復。

我嘗試了以下代碼:

#include <stdio.h>

/* Prints out a combination like {1, 2} */
void printc(int comb[], int k) {
    printf("{");
    int i;
    for (i = 0; i < k; ++i)
        printf("%d, ", comb[i] + 1);
    printf("\\b\\b}\\n");
}


    int next_comb(int comb[], int k, int n) {
    int i = k - 1;
    ++comb[i];
    while ((i >= 0) && (comb[i] >= n - k + 1 + i)) {
        --i;
        ++comb[i];
    }

    if (comb[0] > n - k) /* Combination (n-k, n-k+1, ..., n) reached */
        return 0; /* No more combinations can be generated */

    /* comb now looks like (..., x, n, n, n, ..., n).
    Turn it into (..., x, x + 1, x + 2, ...) */
    for (i = i + 1; i < k; ++i)
        comb[i] = comb[i - 1] + 1;

    return 1;
}

int main(int argc, char *argv[]) {
    int n = 5; /* The size of the set; for {1, 2, 3, 4} it's 4 */
    int k = 3; /* The size of the subsets; for {1, 2}, {1, 3}, ... it's 2 */
    int comb[16]; /* comb[i] is the index of the i-th element in the
            combination */

    /* Setup comb for the initial combination */
    int i;
    for (i = 0; i < k; ++i)
        comb[i] = i;

    /* Print the first combination */
    printc(comb, k);

    /* Generate and print all the other combinations */
    while (next_comb(comb, k, n))
        printc(comb, k);

    return 0;
}

上面的程序打印結果。 我想以某種方式得到結果......但我不能,因為上面的代碼以一種奇怪的方式打印結果。

我們使用一個 int 來表示一個集合。 對於第 i 個位,如果它是 1,則 i 在集合中,反之亦然。

舉個例子:1010(2)={4,2} 1111(2)={4,3,2,1}

對於將要考慮的每個元素,有兩個選擇:在集合中或不在集合中。

所以,總共有 2^n 個不同的集合。 而在我的代碼中,我只是枚舉每個可能的 int 對應一個集合,並輸出相應的集合。

所以我們得到這個代碼:

for(int i=1;i<(1<<n);i++)
{
    for(int j=0;j<n;j++)
        if ((1<<j)&i) printf("%d",j+1);
    puts("");
}

當 n=4 時,輸出:

1
2
12
3
13
23
123
4
14
24
124
34
134
234
1234

如果您想按照給出的順序輸出答案,只需將它們設為字符串並將這些字符串放入向量中並進行排序。

如果 n 很大,則可以使用 bitset。 但是當n>30時,它可能不會以小時為單位終止。 所以 int 是有效的。

這是一個生成數字組合的程序。 它是用 C 編寫的。但它可以用任何其他語言重寫。 現在,只需編譯它並嘗試一下!

#include <stdio.h>
#include <stdlib.h>
int v[100], stack[100];
int sp,i,n,g;
int main()
{
printf("Dimension of V:");
scanf( "%d",&n);
//Input numbers
for (i=0 ; i<n ; i++) {
printf("V[%d]=",i);
scanf( "%d",&g);
v[i]=g;
}
printf("running...\n");
sp=-1;
while(1) {
// stack ones until stack overflow
    while(sp<n-1)  {
      sp=sp+1;
      stack[sp]=1;
      for (i=0 ; i<=sp ; i++) if (stack[i]==1) printf("v[%d]=%d ",i,v[i]);
      printf("\n");
   }
// unstack all the zeros until top of stack is equal one
while (stack[sp]==0 && sp>=0) sp=sp-1;
// if Bottom of stack is reached then stop
if (sp<0) break;
// set top of stack from one to zero
      stack[sp]=0;
  }
return 0;
}

運行 n=4 :

[oldache@localhost fin]$ ./comb
Dimension of V:4
V[0]=10
V[1]=20
V[2]=30
V[3]=40
running...
v[0]=10
v[0]=10 v[1]=20
v[0]=10 v[1]=20 v[2]=30
v[0]=10 v[1]=20 v[2]=30 v[3]=40
v[0]=10 v[1]=20 v[3]=40
v[0]=10 v[2]=30
v[0]=10 v[2]=30 v[3]=40
v[0]=10 v[3]=40
v[1]=20
v[1]=20 v[2]=30
v[1]=20 v[2]=30 v[3]=40
v[1]=20 v[3]=40
v[2]=30
v[2]=30 v[3]=40
v[3]=40

接受的答案中的評論詢問:

“很棒的簡短解決方案,有沒有辦法改變它,使其按順序生成組合?例如 1,2,3,4,12,13,23,14,24,34,123,124,134,234,1234”

以下程序將按該順序生成組合。

該程序的工作方式與已接受的答案相同——使用數字的基礎二進制模式來查找組合。

首先程序顯示 C(4,0),然后是 C(4,1),然后是 C(4,2)、C(4,3),最后是 C(4,4)。

該程序可以輕松擴展。 只需增加 n 的值並在數組中添加適當的 2 次方即可。 雖然效率不高,但該程序確實會生成請求的組合序列。

/* Combin.c -- display the combinations of n objects

   to omit the empty set, C(n,0), change the start value in the for loop in
   the main function from 0 to 1
*/

#include <stdio.h>

int numOfSetBits(int num)
{
    int count = 0;

    while (num > 0) {
        if ((num & 1) == 1) {
            ++count;
        }        
        num /= 2;
    }

    return count;
}

void displayComb(int n, int r)
{
    int power2[] = { 1, 2, 4, 8, 16 };

    for (int i = 0; i < power2[n]; ++i) {
        if (numOfSetBits(i) == r) {
            printf(" {");
            for (int j = 0; j < n; ++j) {
                if (i & power2[j]) {
                    putchar((j + 1) + '0');
                }
            }
            putchar('}');
        }
    }    
}

int main (void)
{
    putchar('\n');

    int n = 4;
    for (int i = 0; i <= n; ++i) {
        printf("C(%d,%d) =", n, i);
        displayComb(n, i);
        putchar('\n');
    }

    return 0;
}

程序 output:

C(4,0) = {}
C(4,1) = {1} {2} {3} {4}
C(4,2) = {12} {13} {23} {14} {24} {34}
C(4,3) = {123} {124} {134} {234}
C(4,4) = {1234}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM