Generating all distinct partitions of a number

后端 未结 5 1911
北海茫月
北海茫月 2020-12-14 12:56

I am trying to write a C code to generate all possible partitions (into 2 or more parts) with distinct elements of a given number. The sum of all the numbers of a g

5条回答
  •  北海茫月
    2020-12-14 13:50

    It is another solution that is based on an iterative algorithm. It is much faster than @imreal's algorithm and marginally faster than @JasonD's algorithm.

    Time needed to compute n = 100

    $ time ./randy > /dev/null
    ./randy > /dev/null  0.39s user 0.00s system 99% cpu 0.393 total
    $ time ./jasond > /dev/null
    ./jasond > /dev/null  0.43s user 0.00s system 99% cpu 0.438 total
    $ time ./imreal > /dev/null
    ./imreal > /dev/null  3.28s user 0.13s system 99% cpu 3.435 total
    
    #include 
    #include 
    #include 
    
    int next_partition(int *a, int* kp) {
        int k = *kp;
        int i, t, b;
    
        if (k == 1) return 0;
        if (a[k - 1] - a[k - 2] > 2) {
            b = a[k - 2] + 1;
            a[k - 2] = b;
            t = a[k - 1] - 1;
            i = k - 1;
            while (t >= 2*b + 3) {
                b += 1;
                a[i] = b;
                t -= b;
                i += 1;
            }
            a[i] = t;
            k = i + 1;
        } else {
            a[k - 2] = a[k - 2] + a[k - 1];
            a[k - 1] = 0;
            k = k - 1;
        }
        *kp = k;
        return 1;
    }
    
    int main(int argc, char* argv[])
    {
        int n = 100;
        int m = floor(0.5 * (sqrt(8*n + 1) - 1));
        int i, k;
        int *a;
        a = malloc(m * sizeof(int));
        k = m;
        for (i = 0; i < m - 1; i++) {
            a[i] = i + 1;
        }
        a[m - 1] = n - m*(m-1)/2;
    
        for (i = 0; i < k; i++) printf("%d ", a[i]);
        printf("\n");
    
        while (next_partition(a, &k)) {
            for (i = 0; i < k; i++) printf("%d ", a[i]);
            printf("\n");
        }
        free(a);
        return 0;
    }
    

提交回复
热议问题