1. Member
Join Date
Feb 2010
Posts
3
Rep Power
0

## Dynamic for loop

Hi,

i am trying to solve this problem where i need combinations of indexes

1. i have a number of drop down boxes. This number can change. Take it as 4 for example
2. each drop down has a number of options which can also vary. Suppose in this case
drop down 1 has 2 values
drop down 2 has 3 values
drop down 3 has 5 values
drop down 4 has 2 values
3. I need to generate permutation of all the values depending on the number of drop downs and number of options in each drop down. i need the index number combinations of all the possible combinations of drop down boxes as output.

4. output in this case needs to be
1111 , 1112, 1121, 1122, 1131, 1132, 1141, 1142, 1151, 1152, 1211, 1212, 1221, 1222, 1231, 1232... and so on.

5. i can not use nested for loop as the number of drop downs can change.

2. Member
Join Date
Feb 2010
Posts
3
Rep Power
0
i had written a sample code for 3 drop downs which is working fine...i just want to make it generic
Java Code:
```public class Test
{
public static void main(String args[])
{
int size = 3;
int [] ls = {2,3,5};
int loop=1;
int length = ls.length;
int [] lInt = new int[length];
int [] vals = new int[length];

for(int i=0;i<length;i++)
{
loop = loop *ls[i];
lInt[i] = ls[i];
vals[i] = 1;
}
System.out.println("loop "+loop);

for(int i=1;i<=loop;i++)
{
if(vals[length-1]<=lInt[length-1])
{
for(int x=0;x<length;x++)
{
System.out.print(vals[x]+" ");
}
System.out.println();
vals[length-1]++;
continue;
}
else
{
vals[length-1] = 1;
vals[length-2]++;
if(vals[length-2]<=lInt[length-2])
{
for(int x=0;x<length;x++)
{
System.out.print(vals[x]+" ");
}
System.out.println();
vals[length-1]++;
}
}
if(vals[length-2]>lInt[length-2])
{
vals[length-1]=1;
vals[length-2]=1;
vals[length-3]++;
for(int x=0;x<length;x++)
{
System.out.print(vals[x]+" ");
}
System.out.println();
vals[length-1]++;
}
}
}
}```

3. Maybe this helps:

Java Code:
```import java.util.Arrays;

public class Combination {

public static boolean combine(int[] c, int[] m) {

for (int i= m.length; --i >= 0;)
if (++c[i] < m[i])
return true;
else
c[i]= 0;
return false;
}

public static void main(String[] args) {

int[] m= { 3, 2, 4 }; 	// the allowed maximum values
do {
System.out.println(Arrays.toString(x));
}
while(combine(x, m));
}
}```
kind regards,

Jos
Last edited by JosAH; 02-07-2010 at 07:45 PM.

4. Member
Join Date
Feb 2010
Posts
3
Rep Power
0
Hey....Thanks Joes....this worked.... :)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•