-3

Given a random integer array and a number x. Find and print the triplets of elements in the array which sum to x. While printing a triplet, print the smallest element first. That is, if a valid triplet is (6, 5, 10) print "5 6 10". There is no constraint that out of 5 triplets which have to be printed on 1st line. You can print triplets in any order, just be careful about the order of elements in a triplet.

import java.util.Arrays;
public class TripletSum {   

    public static void FindTriplet(int[] arr, int x){
        /* Your class should be named TripletSum.
         * Don't write main().
         * Don't read input, it is passed as function argument.
         * Print output and don't return it.
         * Taking input is handled automatically.
         */
       Arrays.sort(arr);
         int b=0, c=0;
     for(int a=0; a<arr.length; a++){
       b=a+1; c=b+1;
       if((arr[a]+arr[b]+arr[c])==x){
        System.out.print(a+"");
        System.out.print(b+"");
        System.out.print(c+"");
       }


       }


     }
}
  • arrayIndexofBoundException due to arr[c] and c = a+2 and a max value is arr.length-1 – Rahul Oct 19 '18 at 12:37
  • When asking about code throwing an error, add that error to your question. – Ivar Oct 19 '18 at 12:38
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Ivar Oct 19 '18 at 12:39
  • Apart from the compilation error, the logic you're using is not correct. You should use some other algorithm because this gives you an incorrect result unless the elements you're looking for are consecutive – suvojit_007 Oct 19 '18 at 12:58

2 Answers2

0

You have to iterarte only till arr.length-2. when a= arr.length-1 then c=arr.length+2 which is the cause of exception

for(int a=0; a<arr.length-2; a++){
     b=a+1; c=b+1;
     if((arr[a]+arr[b]+arr[c])==x){
     System.out.print(a+"");
     System.out.print(b+"");
     System.out.print(c+"");
    }
 }
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
0

You are iterating over the entire length of the array. This will break when you're on the second to last iteration. When the loop indeax a is arr.length - 2, the code within the loop will try to define c as b+1 which is equal to a+2. Now a was arr.length-2 so c will be equal to arr.Length which is a greater index than the array itself (the highest index of an array is it's length minus one.

Pim
  • 554
  • 3
  • 12