implement intPartitions method in MainExercises
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class MainExercises
|
||||
{
|
||||
public char[][] generateTriangle(int n) {
|
||||
@@ -61,37 +63,60 @@ public class MainExercises
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
integer partitioning is a combinatorics problem in discreet maths
|
||||
the problem is to generate sum numbers which their summation is the input number
|
||||
|
||||
e.g. 1 -> all partitions of integer 3 are:
|
||||
3
|
||||
2, 1
|
||||
1, 1, 1
|
||||
|
||||
e.g. 2 -> for number 4 goes as:
|
||||
4
|
||||
3, 1
|
||||
2, 2
|
||||
2, 1, 1
|
||||
1, 1, 1, 1
|
||||
|
||||
Note: As you can see in the examples, we want to generate distinct partitions,
|
||||
which means 1,2 and 2,1 are not different — they count as the same combination.
|
||||
|
||||
You should generate all partitions of the input number.
|
||||
|
||||
Hint: You can determine the size and order of the arrays by finding the pattern
|
||||
of partitions and their count. Trust me, this one's fun and easy :)
|
||||
|
||||
If you're familiar with Lists and ArrayLists, you can also edit the method's
|
||||
body to use them instead of arrays.
|
||||
*/
|
||||
|
||||
public int[][] intPartitions(int n) {
|
||||
// todo
|
||||
return null;
|
||||
int[][] result;
|
||||
ArrayList<ArrayList<Integer>> mainArray = new ArrayList<>();
|
||||
|
||||
ArrayList<Integer> start = new ArrayList<>();
|
||||
start.add(n);
|
||||
mainArray.add(start);
|
||||
|
||||
while (true) {
|
||||
ArrayList<Integer> latestArray = mainArray.get(mainArray.size() - 1);
|
||||
|
||||
Integer numberOfInterest = 0;
|
||||
for (Integer number : latestArray)
|
||||
{
|
||||
if (number > 1) {
|
||||
numberOfInterest = number;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (numberOfInterest == 0) break;
|
||||
|
||||
numberOfInterest--;
|
||||
Integer remain = n - numberOfInterest;
|
||||
ArrayList<Integer> newArray = new ArrayList<>();
|
||||
newArray.add(numberOfInterest);
|
||||
|
||||
for (Integer number = numberOfInterest;;) {
|
||||
if (number >= remain) {
|
||||
newArray.add(remain);
|
||||
break;
|
||||
}
|
||||
else {
|
||||
newArray.add(number);
|
||||
remain -= number;
|
||||
}
|
||||
}
|
||||
|
||||
mainArray.add(newArray);
|
||||
}
|
||||
|
||||
result = new int[mainArray.size()][];
|
||||
|
||||
for (int i = 0; i < mainArray.size(); i++) {
|
||||
ArrayList<Integer> array = mainArray.get(i);
|
||||
|
||||
result[i] = new int[array.size()];
|
||||
|
||||
for (int j = 0; j < array.size(); j++) {
|
||||
result[i][j] = array.get(j);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user