Search code examples
javapermute

All possible permutations of 2D array


Yesterday I asked a question which appeared to be a duplicate, this one, however, I am pretty sure is not a duplicate, as this one is a teeny bit more advanced. The title does not explain all of it, so do carry on reading.

Let us pretend we have a 2D array like so:

{{true, false}, {true, false}, {true, false}, ...}

Now, let us say we would like to loop through all possible permutations of it:

{{false, true}, {true, false}, {true, false}, ...}
{{true, false}, {false, true}, {true, false}, ...}
{{true, false}, {true, false}, {false, true}, ...}
{{false, true}, {true, false}, {false, true}, ...}

And so forth...

Since this adds a level to it, it seriously confuses my mind. We know that the length of the inner arrays are always two, this will never change. That is:

boolean[][] b = new boolean[i][2];

What is the best way to accheive all possible permutations of a 2D array, using Java?

Thank you,


Solution

  • This can apparently be done in the same way any other permutation takes place, you need to loop over the list you would like the permutation to be applied to, and go over all possible combinations of the different elements recursively.

    private void permute(List<List<Boolean>> list, int t)
    {
        for(int i = 0; i < list.size(); i ++)
        {
            Collections.swap(list.get(i), 0, 1);
            permute(list, t + 1);
            Collections.swap(list.get(i), 1, 0);
        }
    
        if(t == list.size() - 1)
            System.out.println("Another permutation.");
    }
    

    And that covers the whole things, all of a sudden you have mapped out all possible combinations of the problem explained above.

    Now let us assume we have three booleans instead of two to switch in a 2D manner, all of a sudden things get slightly more complicated.

    Kind regards,