Home > Net >  Recursion to find the index of an element in an array, where the previous elements sum to a given in
Recursion to find the index of an element in an array, where the previous elements sum to a given in

Time:09-27

I'm attempting to write a recursive method in java to find the index of an element within an array where the element and the elements preceding it sum to a given int (target).

Here is what I have done, I feel like I am close but it isn't giving me the right index for certain targets like 20 for example.

   public class RecursionPractice{

   private static int[] data = {4,1,4,6,2,3,9,5,1,2};

   public static void main(String[] args){
   

      System.out.println("The numbers up until and including index: "   getIndexOfSumRecursive(9,0,0)   ", sum to 9"); // output should be 2
      System.out.println("The numbers up until and including index: "   getIndexOfSumRecursive(20,0,0)   ", sum to 20"); // output should be 5
   
   }
   
   public static int getIndexOfSumRecursive(int target, int total, int i){
      
      total = total   data[i];
      
      if(total >= target){
         return i;
      }else 
     
      return getIndexOfSumRecursive(target-1, total, i 1);
    
   }

}

CodePudding user response:

Write this

return getIndexOfSumRecursive(target, total, i 1);

instead of:

return getIndexOfSumRecursive(target-1, total, i 1);

In other words, doing target-1 makes no sense.

CodePudding user response:

This is quite simple. Actually no need to use recursive here, becuase all you need is just sume first elements untile it will be equal or greater target.

Anyway you can do the same with recursion with same logic.

public static int getIndexOfSumRecursive(int[] arr, int target) {
    return getIndexOfSumRecursive(arr, target, 0, 0);
}

private static int getIndexOfSumRecursive(int[] arr, int target, int i, int curSum) {
    if(i >= arr.length || curSum   arr[i] > target)
        return -1;
    if(curSum   arr[i] == target)
        return i;
    return getIndexOfSumRecursive(arr, target, i   1, curSum   arr[i]);
}
  • Related