Replacing Inner Arrays in a 2D Array Recursively

I want to recursively loop through a 2D array and replace an inner array each time. The problem is that no array seems to be created. Trying to access a value in the array makes java complain that the index used is out-of-bounds.

How can I replace inner arrays in a 2D array using recursion?

I have to replace the arrays dynamically because I want the 2D array to be ragged. Each index should hold an array whose length equals it’s index number + 1.

How I call my method:

double[][] personArr = new double[5][];
personArr = personArrCreator(personArr, 0);

My method:

/**
 * Creates a ragged, pyramid-shaped, 2d array
 * @param pArr The blank 2d Array to fill out
 * @param num Controls the base case.
 * @return double[][] The finished 2d array
 */
 private static double[][] personArrCreator(double[][] pArr, int num) {
    pArr[num] = new double[num];

    if (num == 4) {
       return pArr;
    }

    personArrCreator(pArr, num + 1);
    return null; // never called
 }

Answer

return null; // never called

This actually is called, as once the base case is reached, all the other methods will return null. Instead you want to return the results of the method, by resolving what the recursive call returns to the Array:

return personArrCreator(pArr, num + 1);

Which will return:

[[], [0.0], [0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]

Which will return an Array of size zero. I dont think this is what you want. Instead you could initialize the size as num + 1 to fix this:

private static double[][] personArrCreator(double[][] pArr, int num) {
   pArr[num] = new double[num + 1];
   if (num == 4) {
      return pArr;
   }
   return personArrCreator(pArr, num + 1);
}

Which produces the Array:

[[0.0], [0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]]

Leave a Reply

Your email address will not be published. Required fields are marked *