In Java I want a method that finds all possible combinations when there is a fixed number of slots and a fixed sum total for the values. For example if the sum total is 4 and there are 2 slots then these are all the possible combinations:
[4,0], [3,1], [2,2], [1,3], [0,4]
I already have this recursive method where ‘remainingFacilities’ is the sum total and ‘numberOfTransformers’ is the number of slots, and where all ‘allPossibleFacilityCombinations’ should contain all possible combinations:
private ArrayList<ArrayList<Integer>> allPossibleFacilityCombinations = new ArrayList<>();;
private void distributeFacilities(int remainingFacilities, int numberOfTransformers,
ArrayList<Integer> facilitiesPerTransformer, int currentIndex) {
if (currentIndex == numberOfTransformers) {
if (remainingFacilities == 0) {
// Create a new ArrayList based on facilitiesPerTransformer
ArrayList<Integer> copy = new ArrayList<>(facilitiesPerTransformer);
allPossibleFacilityCombinations.add(copy);
}
return;
}
for (int i = 0; i <= remainingFacilities; i++) {
facilitiesPerTransformer.add(i);
distributeFacilities(remainingFacilities - i, numberOfTransformers, facilitiesPerTransformer,
currentIndex + 1);
facilitiesPerTransformer.remove(facilitiesPerTransformer.size() - 1);
}
}
The problem with this method is it crashes if the number of possible combinations is too large. I specifically need these inputs to work:
totalNumberOfFacilities: 213
numberOfTransformers: 6
In this case the total possible number of combinations is 3917788308. The method crashes before it even gets 1% of the results.
HDNW is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1