recursive Algorithom to loop thru all the values in a list
Hi Guys, Please help me out.
I have a list sayL with N Array lists in that .and i need to loop thru all the values in that to print all combinations.
L = { L1,L2,L3....N}
L1={ 1,2,3,4,5}
L2={aa,bb,cc,dd,ee}
L3={10,20,30}
I need to loop thru all the values and print all like a odometer.
like1,aa,101,aa,20 1,aa,20 1,bb,10 1,bb,20 1,bb,30......5,ee,30.
I think by recursion is the best solution for this .thanks in advance.
# 1
> ...
> like1,aa,101,aa,20 1,aa,20 1,bb,10 1,bb,20
> 1,bb,30......5,ee,30.
That should be 1,aa,30, I presume.
> I think by recursion is the best solution for this
> .thanks in advance.
Here's an iterative algorithm, which I borrowed from user JosAH:
Let's take your example:
L1={ 1,2,3,4,5}, size = 5
L2={aa,bb,cc,dd,ee}, size = 5
L3={10,20,30}, size = 3
Count to 5*5*3 == 75 and for every number i in [0, 75)
Take index
- (i)%5 of the 1st list
- (i/5)%5 for the 2nd list and
- (i/5/3)%3 for the 3rd list
Note that the % operator for the last element is not needed.
# 3
but how can I do the same dinamically..i am trying to do somthing like ..but this doesnt work..i wanto construct a formula for {1,5,5/3};
for(int i=0;i<totElements ;i++) {
System.out.print(i+")");
//int div[] = {1,5,5/3};
int divFactor=1;
for (int j=0;j<3;j++){
ArrayList temp =(ArrayList)allList.get(j);
int thisSize=temp.size();
if (j==0) divFactor = 1;
else
divFactor = thisSize/divFactor;
int co = (i/divFactor )%thisSize;
System.out.print(" "+co);
System.out.print(" Div Factor "+divFactor);
}
}>
# 5
> lets say if i have this what i should do ? my Lists
> are dynamic ..
> ...
That doesn't matter. Here's some pseudo code:
public class Foo {
private static void generate(String[][] arrays) {
int 'idx' <- the product of the lengths of the entries in 'arrays'
WHILE 'idx' is more than zero
int 'j' <- 1
FOR every 'a' in 'arrays'
print index ('idx'/'j')%'a'.length from 'a'
j <- j * 'a'.length
END FOR
print a new line and decrease 'idx'
END WHILE
}
public static void main(String[] args) {
generate(new String[][] {
{"1","2","3","4","5"},
{"aa","bb","cc","dd"},
{"10","20","30"},
{"AA","BB"},
{"100","200","300","400"}
}
);
}
}
Try to finish it.
Good luck.