1

What I'm asking is how can I initiallize a list of all the different variations of an array of a specified size holding a specified number of the same element?

So for example an array of size 5 holding three of the same element could be done in these ways, where X's are the elements and O's are the empty spaces.

1) [X, X, X, O, O]

2) [X, X, O, X, O]

3) [X, X, O, O, X]

4) [X, O, X, X, O]

5) [X, O, X, O, X]

6) [X, O, O, X, X]

7) [O, X, X, X, O]

8) [O, X, X, O, X]

9) [O, X, O, X, X]

10) [O, O, X, X, X]

What algorithm could be used to create this kind of result?

4

1 回答 1

1

您可以使用递归算法来生成所有可能的排列:

public static void main(String[] args) {
    ArrayList<char[]> list = new ArrayList<char[]>();
    char[] c = {'O', 'O', 'O', 'O', 'O'};
    nextArray(list, c, 0, 3);
}

public static void nextArray(List<char[]> list, char[] array, int index, int changes) {
    if(index == array.length) return;
    if(changes == 0) {
        list.add(array);
        return;
    }

    char[] a1 = Arrays.copyOf(array, array.length);
    a1[index] = 'X';

    nextArray(list, a1, index+1, changes-1);
    nextArray(list, Arrays.copyOf(array, array.length), index+1, changes);
}

想法是一次更改一个索引(跟踪更改索引的次数),直到changes = 0. 然后添加该数组并终止该分支以进行递归。

于 2016-04-06T04:15:23.963 回答