void partitionOddandEvenHelper(int N, int * partition, int pos) { //BASE CASE if(N == 0) { printPartition(partition, pos); return; } //INDUCTIVE CASE int i; for(i = 1; i <= N; i++) { int val = 0; if(pos == 0) { val = 1; } else { val = (partition[pos - 1] % 2) != (i % 2); } if(val == 1) { partition[pos] = i; partitionOddandEvenHelper(N - i, partition, pos + 1); } } }
void partitionOddAndEven(int value) { printf("partitionOddAndEven %d\n", value); int n=value; if (n <= 0) { return; } int * arr; arr = malloc(sizeof(int) * n); partitionOddandEvenHelper(arr, 0, n); free (arr); return; }
/* * ================================================================= * This function prints alternate ood and even number partitions of a positive integer value. Each partition starts from and odd number, even number, ood number again, even number again...etc. * * For example, if value is 6 * 1 + 2 + 1 + 2 and * 3 + 2 + 1 are valid partitions * * 6 is not a valid partition * * 2 + 1 + 1 + 2 and * 2 + 1 + 3and * 5 + 1 are invalid partitions. * * The program should generate only valid partitions. Do not * generates invalid partitions and checks validity before printing. */ void partitionOddandEvenHelper(int * part, int ind, int left) { int val; if (left == 0) { printPartition(part, ind); return; } for (val = 1; val <= left; val ++) { if((val%2 ==1 && ind%2==0) || ((val%2==0 && ind%2==1))) { part[ind] = val; partitionOddandEvenHelper(part, ind + 1, left - val); } } }
void partitionOddAndEven(int value) { int *partition = malloc(sizeof(int) * value); partitionOddandEvenHelper(value, partition, 0); free(partition); }