This is the second solution to find the triplets of numbers in which their sum is divisible by 9 from an array of integers. This method uses the core logic of traversing array using 3 nested for loops, add any three numbers come across in each iteration, and then uses simple predicate to verify that the sum is divisible by 9.
import java.util.function.Predicate;
public class Divby9 {
public static void divBy9Triplets(int[] tempArr,Predicate<Integer> div9) {
System.out.println("The hardcoded array of integers given below");
System.out.print("[ ");
for(int i=0;i<tempArr.length;i++)
System.out.print(tempArr[i]+" ");
System.out.println("]");
/*Traverse through the array using nested for loop, and check whether
*the sum of the successive numbers divisible by 9 */
System.out.println("The triplets of numbers which are divisible by 9");
for (int i=0;i<tempArr.length;i++)
for(int j=i+1;j<tempArr.length;j++)
for(int k=j+1;k<tempArr.length;k++)
if (div9.test(tempArr[i]+tempArr[j]+tempArr[k]))
System.out.println(tempArr[i]+" "+tempArr[j]+" "+tempArr[k]);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] intArr= {14,20,11,5,29,17,58};
System.out.println("OUTPUT:");
//Calling the function divby9 which computes the sum of triplets divisible by 9
divBy9Triplets(intArr, (i)-> i%9==0);
}
}
OUTPUT:
The hardcoded array of integers given below
[ 14 20 11 5 29 17 58 ]
The Triplets of numbers which are divisible by 9
14 20 11
14 20 29
14 11 29
14 5 17
20 11 5
20 5 29
11 5 29

Leave a reply to Toney Cornmesser Cancel reply