multiple arrays permutation and combination in Java

To achieve the permutation and combination of multiple arrays, you can use the recursive method. The specific steps are as follows:

  1. Create a recursive function that takes three parameters: the original array collection, the current permutation result, and the current index of the array being processed.
  2. In the recursive function, the first step is to check if the current index being processed exceeds the length of the original array set. If it does exceed, then the current permutation result is added to the final result set.
  3. If the current index of the array being processed has not exceeded the length of the original array collection, retrieve the current array being processed, iterate through all elements in the array, and add each element to the current permutation result.
  4. Call the recursive function itself, passing the current permutation result and the next array index as parameters.
  5. After the recursive function ends, return the final result set.

Here is a sample code:

import java.util.ArrayList;
import java.util.List;

public class ArrayPermutation {

    public static List<List<Integer>> permute(int[][] arrays) {
        List<List<Integer>> result = new ArrayList<>();
        permuteHelper(result, new ArrayList<>(), arrays, 0);
        return result;
    }

    private static void permuteHelper(List<List<Integer>> result, List<Integer> current, int[][] arrays, int index) {
        if (index >= arrays.length) {
            result.add(new ArrayList<>(current));
            return;
        }

        int[] array = arrays[index];
        for (int i = 0; i < array.length; i++) {
            current.add(array[i]);
            permuteHelper(result, current, arrays, index + 1);
            current.remove(current.size() - 1);
        }
    }

    public static void main(String[] args) {
        int[][] arrays = {
                {1, 2, 3},
                {4, 5},
                {6, 7, 8}
        };

        List<List<Integer>> result = permute(arrays);
        for (List<Integer> list : result) {
            System.out.println(list);
        }
    }
}

The output result is:

[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]
[3, 4, 6]
[3, 4, 7]
[3, 4, 8]
[3, 5, 6]
[3, 5, 7]
[3, 5, 8]

The code above achieves the permutation and combination of three arrays. You can modify the original array set as needed to achieve the permutation and combination of any number of arrays.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds