0

I have a little problem with this.I want to generate every possible combination.The numbers located in 1D array and it is read from a file. Now I don't know the problem: I know that every combination which will be printed to monitor is in ascending order. The probelm is that if it finishes with smallest number it doesn't ascends to the next number.

Example: The 1D array file with 1,2,3,4,5 and n = 5 and p = 3; Possible combinations:

1 2 3, 1 2 4, 1 2 5, 1 3 4, 1 3 5, 1 4 5, 2 3 4, 2 3 5, etc...

Here is what I done so far:

#include <stdio.h>
#include <stdlib.h>

void print(int*,int);
void combination(int*,int,int,int);
int main()
{
    FILE *fin = fopen("bemenet.txt","r");
    if(!fin){printf("Error opening file @!!!");return 0;}
    int *a,i,n,p = 3;
    fscanf(fin,"%i ",&n);
    a = (int*)malloc(n*sizeof(int));
    for(i = 0; i < n; ++i){
        fscanf(fin,"%i ",&a[i]);
    }
    combination(a,n,p,0);

    return 0;
}

void combination(int *a,int n,int p,int k)
{
    int i;
    if(k == p){
        print(a,k);
    }
    else{
        for(a[k + 1] = a[k] + 1 ; a[k+1] < n; ++a[k+1]){
            combination(a,n,p,k+1);
        }
    }
}
void print(int *a,int k)
{
    int i;
    for(i = 0; i < k; ++i){
        printf("%i ",a[i]);
    }
    printf("\n");
}
4

1 回答 1

0

数字只会增加的原因是,您永远不会减少它们。而且这个条件a[k+1] < n对我来说没有任何意义,你为什么要将字段的大小与数组的元素(可以是例如 1000)进行比较?此外,您不应该更改数组中的元素,++a[k+1]因为没有理由这样做。

参见例如 生成列表所有可能排列的算法? 寻求更多帮助。

于 2016-03-27T18:12:11.850 回答