Given an array of integers [x0 x1 x2], how do you calculate all possible permutations from [0 0 0] to [x0 x1 x2]?

拥有回忆 提交于 2020-01-03 17:28:20

问题


I am writing a program that takes in an ArrayList and I need to calculate all possible permutations starting with a list of zeroes, up to the value in the corresponding input list.

Does anyone know how to iteratively calculate these values?

For example, given [ 1 2 ] as input, it should find and store the following lists:

[0 0], [1 0], [1 1], [1 2], [0 1], [0 2]

Thanks!


回答1:


Here's a standard recursive generator:

import java.util.Arrays;

//...

static void generate(int... limits) {
    generate(new int[limits.length], limits, 0);
}
static void generate(int[] arr, int[] limits, int n) {
    if (n == limits.length) {
        System.out.println(Arrays.toString(arr));
    } else {
        for (int i = 0; i <= limits[n]; i++) {
            arr[n] = i;
            generate(arr, limits, n + 1);
        }
    }
}

//....

generate(1, 2);
/* prints
[0, 0]
[0, 1]
[0, 2]
[1, 0]
[1, 1]
[1, 2]
*/

This works in the same way as if you've had written variable number of nested loops. With recursion, you only have to write one loop, and it can actually have variable nesting depth (infinite if you're not careful!).


There's also the iterative i.e. non-recursive version:

static void generateI(int... limits) {
    int[] arr = new int[limits.length];
    int n;
    do {
        System.out.println(Arrays.toString(arr));
        n = limits.length - 1;
        while (n >= 0 && arr[n] == limits[n]) {
            arr[n] = 0;
            n--;
        }
        if (n >= 0) arr[n]++;
    } while (n >= 0);
}

This works in much the same way that increment by 1 works in binary arithmetic (or any base, really), except each position has its own limit.

For example, in base 10, here's how you increment:

 12399
     ^ (is highest digit, therefore set to 0, move left)

 12390
    ^ (is highest digit, therefore set to 0, move left)

 12400
   ^ (not the highest digit, add 1, DONE!)



回答2:


It doesn't look like you actually want permutations. If you are given an array X = [1, 2], its permutations are exactly [1, 2] and [2, 1]. Going by your example, you want it to generate all tuples z where 0 <= z <= X.

This tuple-listing problem is nicely solved by polygenelubricants's solution. Your stated permutation problem is solved by Fazal's solution.



来源:https://stackoverflow.com/questions/2664800/given-an-array-of-integers-x0-x1-x2-how-do-you-calculate-all-possible-permuta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!