Me estoy rascando la cabeza tratando de hacer esto y me está comiendo. Sé que no es TAN complejo. Tengo varios artículos, este número puede ser igual o mayor a tres. Entonces necesito determinar la combinación posible de grupo de elementos que completará el total. La única restricción es que los grupos deben tener tres o más elementos, sin exceder (pero incluir) siete elementos.Algoritmo para determinar posibles grupos de elementos
Por ejemplo:
Si tengo 7 artículos, entonces podría tener estos posibles grupos:
- 1 grupo de 7 elementos.
- 1 grupo de 4 elementos y 1 grupo de 3 elementos.
Si tengo 12 artículos, que podría tener estos posibles grupos:
- 4 grupos de 3 elementos.
- 3 grupos de 4 elementos.
- 2 grupos de 6 elementos.
- 1 grupo de 7 elementos + 1 grupo de 5 elementos.
- 2 grupos de 3 y 1 grupo de 6 elementos.
- 1 grupo de 3, 1 grupo de 4 y 1 grupo de cinco elementos.
- ...
pensé en la recursividad y empezó a ejecutar el algoritmo. Obviamente no está funcionando. Yo chupo en la recursión. Mucho.
//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);
}
}
}
}
}
Gracias por su ayuda !!!
Esto es muy parecido a lo que estoy buscando. Estoy tratando de convertirlo a Java para ver cómo funciona. Gracias. – miguelrios