Home > Software engineering >  fill array with recursive method
fill array with recursive method

Time:08-24

I m trying to create a function to fill array with the recursive method in java this is my code (the parameter x is the size of the array):

public int[] genArr(int[] nums,int idx,int x){
    if(idx>x){
        return nums;
    }
   
    else{
    nums[idx] = idx;
    return genArr(nums,idx  ,x--);
    }
     
}

but when run my function I have stackOverflow error.

Somebody can help me ?

CodePudding user response:

There are a couple of problems there:

  1. The stack overflow issue you asked about.

  2. The basic logic of the method.

The first problem is that getArr(num, idx , x--) uses the postfix increment operator (the is after the operand), so it passes the current value of idx to getArr and then increments the parameter's value. But nothing ever uses the incremented parameter value. So if idx is 0 and x is 10, you're endlessly calling getArr(nums, 0, 10) until you overflow the stack. If you were going to use the increment operator, it would need to be the prefix increment operator where the is in front of the operand ( idx), but there's no reason to use the increment operator: just use idx 1.

The second problem is that even if you fix the above, by increasing idx and decreasing x and stopping when idx > x is true, you're going to miss out filling in most of the array. For instance, if you started with idx at 0 and x at 10, your code would stop when idx was 6 and x was 4, leaving the last several slots of your array uninitialized: [0, 1, 2, 3, 4, 5, 0, 0, 0, 0]. Instead, get rid of x entirely and make idx >= nums.length your termination condition:

public int[] genArr(int[] nums, int idx) {
// #2 No `x` −−−−−−−−−−−−−−−−−−−−−−−−−−^
    if (idx >= nums.length) {
// #2 −−−−−−^^^^^^^^^^^^^^ compare with `nums.length`
        return nums;
    } else {
        nums[idx] = idx;
        return genArr(nums, idx   1);
// #1 −−−−−−−−−−−−−−−−−−−−−−^^^^^^^
    }
}

Technically, you could use == rather than >= because you only ever add 1 to idx, but I tend to be paranoid about array access guards like that and use >= instead (in case logic changes and we add more than 1 at some point).

  • Related