Return the cross product of a list of lists

后端 未结 4 2261
攒了一身酷
攒了一身酷 2021-01-17 09:06

Given a list of size n, Write a program that returns all possible combination of elements contained in each list.

Example:

  • List A = \"x, z\"
4条回答
  •  灰色年华
    2021-01-17 09:09

    As you know, the usual solution is recursion. However, out of boredom I once wrote a java method multiNext to do this without recursion. multiNext uses an array to keep track of a load of indices in an equivalent system of nested loops.

    public static boolean multiNext(int[] current, int[] slotLengths) {
        for (int r = current.length - 1; r >= 0; r--) {
            if (current[r] < slotLengths[r] - 1) {
                current[r]++;
                return true;
            } else {
                current[r] = 0;
            }
        }
        return false;
    }
    
    public static void cross(List> lists) {
        int size = lists.size();
        int[] current = new int[size];
        int[] slotLengths = new int[size];
        for (int i = 0; i < size; i++)
            slotLengths[i] = lists.get(i).size();
        do {
            List temp = new ArrayList<>();
            for (int i = 0; i < size; i++)
                temp.add(lists.get(i).get(current[i]));
            System.out.println(temp);
        } while (multiNext(current, slotLengths));
    }
    
    public static void main(String[] args) {
        cross(Arrays.asList(Arrays.asList("x", "z"), Arrays.asList("a", "b", "c"), Arrays.asList("o", "p")));
    }
    

提交回复
热议问题