-4

We have to find sum of array and then return if the value is odd (boolean) using recursion

A = {87, 31, 15, 25, 10, 15, 21, 75)
methodname(A, pos) //position is 0 at the begining

i did this so far, but i'm way off since i can't sum and return boolean in the same line

if (pos == array.length-1) {
    return A[pos] % 2 != 0
} else {
    if (pos < A.length - 1)
        return A[pos] + methodname(A, pos + 1) % 2 == 1;
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Asrar
  • 13
  • 2

2 Answers2

2
public static void main(String[] args) {
    System.out.println(isSumOdd(new int[]{3, 3, 4}, 0));
}

private static boolean isSumOdd(int[] arr, int pos) {
    return pos == arr.length - 1
            ? arr[pos] % 2 != 0
            : isSumOdd(arr, pos + 1) ^ arr[pos] % 2 != 0; //Sum of 2 numbers can be odd iff exactly one of them is odd.
}
Kartik
  • 7,677
  • 4
  • 28
  • 50
  • @Asrar Why not? – Scary Wombat Oct 17 '18 at 02:08
  • I see ? and : in the code. What is that for? am i missing something – Asrar Oct 17 '18 at 02:12
  • @Asrar it's called ternary operator. This is equivalent to writing `if (pos == arr.length - 1) { return arr[pos] % 2 != 0; } else { return isSumOdd(arr, pos + 1) ^ arr[pos] % 2 != 0; }` – Kartik Oct 17 '18 at 02:15
  • 2
    @Asrar *This solution is not even close* is a pretty rude comment to make when you do not even understand the code. I think you should apologize to Kartlik who has gone to the trouble to help you. – Scary Wombat Oct 17 '18 at 02:30
  • @ScaryWombat I said "2 numbers", you gave example of 3 numbers :). Anyway, would you like me to remove that line? No apologies needed, non-native speakers can sometimes sound rude while they don't actually mean it (me being one of them). – Kartik Oct 17 '18 at 02:33
  • My bad if i said something wrong. But i never came across ^ in java yet. May be i have to learn a lot yet – Asrar Oct 17 '18 at 02:37
  • Moved that line to the right place to avoid confusion. @Asrar ^ is [XOR operator](https://stackoverflow.com/a/726665/1039555). – Kartik Oct 17 '18 at 02:45
0

You can try using the following approach (syntax might be wrong, treat the following as pseudo code):

  // gives whether the sum from i to end 
  // is even or odd 
  Boolean sumIsEven(int[] arr, int i ){

      //base case
      if(arr.length-1==i){
           return arr[i]%2 ==0;
      }

      if(arr[i]%2 == 0){
           return sumIsEven(arr, i +1);
      }else{
           // arr[i] is odd
           return !sumIsEven(arr, i +1);
      }
}

But this will give only if the whole sum is odd/even

mettleap
  • 1,390
  • 8
  • 17