I am scratching my head trying to do this and it's eating me up. I know it is not THAT complex. I have a number of items, this number can be equal or greater than three. Then I need to determine the possible combination of group of items that will complete the total. The only restriction it's that the groups should have three or more items, not exceeding (but including) seven items.
For example:
If I have 7 items, then I could have these possible groups:
- 1 group of 7 items.
- 1 group of 4 items and 1 group of 3 items.
If I have 12 items, I could have these possible groups:
- 4 groups of 3 items.
- 3 groups of 4 items.
- 2 groups of 6 items.
- 1 group of 7 items + 1 group of 5 items.
- 2 groups of 3 and 1 group of 6 items.
- 1 group of 3, 1 group of 4 and 1 group of five items.
- ...
I thought about recursion and started implementing the algorithm. It's obviously not working. I suck at recursion. A lot.
//Instance Fields
public List<ArrayList<String>> options;
//Method that will generate the options. The different options are
//stored in a list of "option". An individual option will store a list of
//strings with the individual groups.
public void generateOptions(int items, ArrayList<String> currentOption){
//If the current option is null, then create a new option.
if(currentOption == null){
currentOption = new ArrayList<String>();
}
if(items < 3){
//If the number of items is less than three then it doesn't comply with the
//requirements (teams should be more or equal than three.
currentOption.add("1 group of "+items+" items");
options.add(currentOption);
}
else{
//I can make groups of 3,4,5,6 and 7 items.
for(int i = 3;i<=7;i++){
if(items%i == 0){
// If the number of items is divisible per the current number,
// then a possible option could be items/i groups of i items.
// Example: Items = 9. A possible option is 3 groups of 3 items.
currentOption.add(items/i +" groups of "+ i+" items");
options.add(currentOption);
}
else{
// If the number of items - the current number is equal or greater than
// three, then a possible option could be a group of i items
// and then I'll have items-i items to separate in other groups.
if(items - i >=3){
currentOption.add("1 group of "+i+" items");
generateOptions(items-i,currentOption);
}
}
}
}
}
Thanks for your help!!!