I need to find one of the possible partitions of a number (N) by the number of elements (M) involved, like this:
Number 4
Partitions
4
3 1
2 2
2 1 1
1 3
1 1 1 1
I need to create a function P(N, M), that would return the following result for the call P(4, 2):
3 1
2 2
1 3
I've created the following methods, but I couldn't find a way to break the lines between each partition:
List<String> partitions;
public String[] partitionWithNElements(int n, int numberOfElements) {
partitions = new ArrayList<String>();
partition(n, n, "");
String[] arrayPartition = null;
for (int i = 0; i < partitions.size(); i++) {
arrayPartition = partitions.get(i).split("#");
if (arrayPartition.length == numberOfElements)
break;
}
return arrayPartition;
}
private void partition(int n, int max, String prefix) {
if (n == 0) {
if (prefix.startsWith("#"))
prefix = prefix.substring(1);
partitions.add(prefix);
return;
}
for (int i = Math.min(max, n); i >= 1; i--) {
partition(n - i, i, prefix + "#" + i);
}
}
Code updated once again. Now I'm using a string to return the elements and I've been able to achieve the expected results, however I'm trying to find a solution without using String to return the partitions, so I won't need to use String split function.