Search code examples
javaarraysrecursionjava-7dimensions

Get all indexes of a multidimensional table


I am having trouble to create a (recursive) function that prints all possible indexes for a multi dimensional table.
I got the information about the multi-dimensionality as an array.
Example: int[]{6,6} would be a 2-dimensional table with 6x6 = 36 fields, so the result would be [0,0],[0,1],[1,1],[1,2],[2,2]... and so on.
Another example:
int[]{2,2,2} would be a 3-dimensional table with 8 possible indexes: [0,0,0],[0,0,1],[0,1,1]... and so on
I'm trying to do this in Java 7.

Edit: As requested, what I got so far. Code is producing OutOfBound Exception.

loop(new int[2], new int[]{6, 6}, 0);

  private void loop(int[] index, int[] dimensionSizes, int dimensionIndex) {
        if (index[dimensionIndex] < dimensionSizes[dimensionIndex] && dimensionIndex < dimensionSizes.length) {
            System.out.println(Arrays.toString(index));
            index[dimensionIndex] = index[dimensionIndex] + 1;
            if (index[dimensionIndex] < dimensionSizes[dimensionIndex]) {
                loop(index, dimensionSizes, dimensionIndex);
            } else {
                loop(index, dimensionSizes, dimensionIndex + 1);
            }
        }
    }

Solution

  • I think this code could respond to your question:

    public static void printAllIndex(int[] dimensions) {
        int[] index = new int[dimensions.length];
        int stepNumber = 0;
    
        // Initialization
        for (int i : index) { index[i] = 0; }         // init index to 0
        for (int d : dimensions) { stepNumber += d; } // count number of iteration needed
        System.out.println(Arrays.toString(index));   // print first index [0,0,...]
    
        for(int s = 0; s <= stepNumber - 1; s++) {
            boolean allEquals = true;
            int value = index[index.length - 1];
            for (int i = index.length - 1; i >= 0; i--) {
                if(index[i] != value) {
                    index[i]++;
                    allEquals = false;
                    break;
                }
            }
            if (allEquals) { index[index.length - 1]++; }
            System.out.println(Arrays.toString(index));
        }
    }