Eliminating Recursion
<p>I've just been looking at the following piece of code</p>

<pre><code>package test;

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

public class Main {

    public static void main(final String[] args) {

        final int sizeA = 3;
        final int sizeB = 5;

        final List&lt;int[]&gt; combos = getAllCombinations(sizeA-1, sizeB);

        int counter = 1;
        for(final int[] combo : combos) {
            System.out.println("Combination " + counter);
            System.out.println("--------------");
            for(final int value : combo) {
                System.out.print(value + " ");
            }
            System.out.println();
            System.out.println();
            ++counter;
        }

    }

    private static List&lt;int[]&gt; getAllCombinations(final int maxIndex, final int size) {

        if(maxIndex &gt;= size)
            throw new IllegalArgumentException("The maximum index must be smaller than the array size.");

        final List&lt;int[]&gt; result = new ArrayList&lt;int[]&gt;();

        if(maxIndex == 0) {
            final int[] array = new int[size];
            Arrays.fill(array, maxIndex);
            result.add(array);
            return result;
        }

        //We'll create one array for every time the maxIndex can occur while allowing
        //every other index to appear, then create every variation on that array
        //by having every possible head generated recursively
        for(int i = 1; i &lt; size - maxIndex + 1; ++i) {

            //Generating every possible head for the array
            final List&lt;int[]&gt; heads = getAllCombinations(maxIndex - 1, size - i);

            //Combining every head with the tail
            for(final int[] head : heads) {
                final int[] array = new int[size];
                System.arraycopy(head, 0, array, 0, head.length);
                //Filling the tail of the array with i maxIndex values
                for(int j = 1; j &lt;= i; ++j)
                    array[size - j] = maxIndex;
                result.add(array);
            }

        }

        return result;

    }

}
</code></pre>

<p>I'm wondering, how do I eliminate recursion from this, so that it returns a single random combination, rather than a list of all possible combinations?</p>

<p>Thanks</p>
