Search code examples
arraysalgorithmpermutation

How do I create every version of an array of a specified size with a specified number of elements?


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?


Solution

  • You could use a recursive algorithm to generate all possible permutations:

    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);
    }
    

    The idea is to change one index at a time (keeping track of the number of times you change an index), until changes = 0. Then you add that array and terminate that branch for the recursion.