I have a list of lists in Java:
{{1,2},{3,4,5},{6,7,8}}
I try to find all permutations of this list. Meaning, In the result I would get a list with the next:
{{1,3,6},{1,3,7},{1,3,8},{1,4,6}....{2,5,8}}
Is there a reasonable way to do it?
I have a list of lists in Java:
{{1,2},{3,4,5},{6,7,8}}
I try to find all permutations of this list. Meaning, In the result I would get a list with the next:
{{1,3,6},{1,3,7},{1,3,8},{1,4,6}....{2,5,8}}
Is there a reasonable way to do it?
Here is List<List<Integer> implementation.
static public void main(String[] argv) {
    List<List<Integer>> lst = new ArrayList<List<Integer>>();
    lst.add(Arrays.asList(1, 2));
    lst.add(Arrays.asList(3, 4, 5));
    lst.add(Arrays.asList(6, 7, 8));
    List<List<Integer>> result = null;
    result = cartesian(lst);
    for (List<Integer> r : result) {
        for (Integer i : r) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
static public List<List<Integer>> cartesian(List<List<Integer>> list) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    int numSets = list.size();
    Integer[] tmpResult = new Integer[numSets];
    cartesian(list, 0, tmpResult, result);
    return result;
}
static public void cartesian(List<List<Integer>> list, int n,
                             Integer[] tmpResult, List<List<Integer>> result) {
    if (n == list.size()) {
        result.add(new ArrayList<Integer>(Arrays.asList(tmpResult)));
        return;
    }
    for (Integer i : list.get(n)) {
        tmpResult[n] = i;
        cartesian(list, n + 1, tmpResult, result);
    }
}
 
    
    Do you mean like this?
int[] list1 = {1, 2}, list2 = {3, 4, 5}, list3 = {6, 7, 8};
for (int i : list1) for (int j : list2) for (int k : list2) {
    // something
}
If you value an unknown number of lists, the simplest approach might be recursion.
public void cartesian(int[][] lists) {
    cartesian(lists, new int[lists.length], 0);
}
public void cartesian(int[][] lists, int[] values, int n) {
    if (n == lists.length) {
        System.out.println(Arrays.toString(values));
    } else {
        for (int i : lists[n]) {
            values[n] = i;
            cartesian(lists, values, n + 1);
        }
    }
}
