Jay Patel
Jay Patel

Reputation: 1346

Dynamic Nested for loop using recursion (All Permutations)

I was trying to implement something like this.

I have bunch of lists.

Each list has certain numbers.

A - 1,2,3    
B - 4,5    
C - 6,7,8    

I want to find all permutations of A, B, C list That is:

1,4,6    
1,4,7    
1,4,8    
1,5,6    
1,5,7    
1,5,8    
2,4,6
and so on...

I could have done this using for loop, but the number of lists are not static.

So I tried using recursion.

Here is what I tried: Calling :

nested(number_of_lists,0, array list of array, current_permutation);

And the function:

static void nested(int depth, int index, ArrayList< ArrayList<Integer> > list, ArrayList<Integer> curr)
{

    if(depth==0)
    {


        ArrayList <Integer> x = new ArrayList<>();
        int i;
        for( i=0;i<curr.size();i++)
        {
            System.out.println(curr.get(i));

            x.add(curr.get(i));
        }
        global.add(x);

        curr.remove(curr.size()-1);

    }
    else
    {

        for(int i=0;i<list.get(index).size();i++)
        {

            curr.add(list.get(index).get(i));

            nested(depth-1, index+1, list, curr);

            if( curr.size()==list.get(index).size())
            {
                curr.remove(curr.size()-1);
            }

            if(index==0 &&(curr.size()-1) == i)
                curr = new ArrayList<>();


        }
    }

}

Global is new array list of array list which had all permutations stored.

But, after two permutations with A, I get wrong answer

1 4 6 
1 4 7 
1 4 8 
1 5 6 
1 5 7 
1 5 8 
2 4 6 
2 4 7 
2 4 8 
2 5 6 
2 5 7 
2 5 8 
2 3 4 6 
2 3 7 
2 3 8 
2 5 6 
2 5 7 

and so on..

Where is the code doing wrong. My first two permutations with two elements of A are perfectly fine. Sorry for such a long explanation. Some help would be appreciated.

Upvotes: 1

Views: 859

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37665

You appear to be making this more complicated than it actually is. I have managed to correct this just by commenting out some of your lines.

static void nested(int depth, int index, ArrayList< ArrayList<Integer> > list, ArrayList<Integer> curr)
{

    if(depth==0)
    {


        ArrayList <Integer> x = new ArrayList<>();
        int i;
        for( i=0;i<curr.size();i++)
        {
            System.out.println(curr.get(i));

            x.add(curr.get(i));
        }
        global.add(x);

        //curr.remove(curr.size()-1);

    }
    else
    {

        for(int i=0;i<list.get(index).size();i++)
        {

            curr.add(list.get(index).get(i));

            nested(depth-1, index+1, list, curr);

            //if (curr.size()==list.get(index).size())
            //{
                curr.remove(curr.size()-1);
            //}

            //if(index==0 &&(curr.size()-1) == i)
            //    curr = new ArrayList<>();


        }
    }

}

Upvotes: 1

Related Questions