Popular Posts

Monday, March 21, 2011

Compositions of a number


/******************************************************************************
*
*Given a number n, write a program to output its various compositions
*where order is not important.
*
*For eg, for 5, it will be
*
*1 + 4
*1 + 1 + 3
*1 + 1 + 1 + 2
*1 + 1 + 1 + 1 + 1
*1 + 2 + 2 and so on
*
*
******************************************************************************
/

 

public class composite {

public static void main(String[] args) {
int[] arr = new int[20];
int n = 4;
new composite().getCompositions(n, 0, arr);
}

/*
* The function prints all combinations of numbers 1, 2, ...MAX_POINT that
* sum up to n. i is used in recursion keep track of index in arr[] where
* next element is to be added. Initital value of i must be passed as 0
*/
void getCompositions(int n, int i, int[] arr) {
if (n == 0) {
printArray(arr, i);
} else if (n > 0) {
for (int k = 1; k <= n; k++) {
arr[i] = k;
getCompositions(n - k, i + 1, arr);
}
}
}

void printArray(int[] arr, int size) {
System.out.println();
for (int i = 0; i < size; i++) {
System.out.print(" " + arr[i] + " ");
}
}

}



No comments:

Post a Comment