This is the first solution to find array triplets, with sum of any two numbers equals with any other element in the same array.
public class SumofNnumbers {
public static void main(String[] args) {
int [] numArray= {50, 108, 47, 61, 34, 184, 97, 71, 87};
int arrLen=numArray.length;
System.out.println("The given array of numbers are");
System.out.print("[");
for (int i=0;i<arrLen;i++)
System.out.print(numArray[i]+" ");
System.out.println("]");
System.out.println("Triplets -> Sum of any two numbers must be available in the array itself");
System.out.println("FirstNum SecondNum SumNum");
/* Nested for loop designed here to find sum of all possible pairs,
* and call the boolean function SrchSumInArr to check whether this sum
is available as one of the numbers in array itself. */
for(int i=0;i<arrLen;i++)
for (int j=i+1;j<arrLen;j++)
if (SrchSumInArr(numArray[i]+numArray[j],numArray))
System.out.println(numArray[i]+" "+numArray[j]+" "+(numArray[i]+numArray[j]));
}
private static boolean SrchSumInArr(int sumVal, int[] tmpArray) {
// Search the calculated sum in the array, if not found return false
boolean numFound=false;
for(int i=0;i<tmpArray.length;i++)
if(tmpArray[i]==sumVal)
numFound=true;
return numFound;
}
}
OUTPUT:
The given array of numbers are
[50 108 47 61 34 184 97 71 87 ]
Triplets -> Sum of any two numbers must be available in the array itself
FirstNum SecondNum SumNum
50 47 97
47 61 108
97 87 184

Leave a comment