This is the second solution to find array triplets, with sum of any two numbers equals with any other element in the same array. This approach uses functional interface and lambda expression.
//Define the functional interface with 'checkSumInArray' abstract method.
interface Triplets {
public boolean checkSumInArray(int a, int[] b);
}
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");
/* Define the Lambda expression for 'Triplets' functional interface */
Triplets csa = ((sumVal, tmpArr) -> {
boolean numFound = false;
for (int i = 0; i < tmpArr.length; i++)
if (tmpArr[i] == sumVal)
numFound = true;
return numFound;
});
for (int i = 0; i < arrLen; i++)
for (int j = i + 1; j < arrLen; j++)
if (csa.checkSumInArray(numArray[i] + numArray[j], numArray))
System.out.println(numArray[i] + " " + numArray[j] + " " + (numArray[i] + numArray[j]));
}
}
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