How to count and print triplets from an array with sum smaller than a given value in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        int[] array = {4, 5, 2, 8, 1, 3, 8, 7, 10};
	    int size = array.length;
	    int sum = 11;
	    int count = 0;

	    for (int i = 0; i < size - 2; i++) {
		    for (int j = i + 1; j < size - 1; j++) {
			    for (int k = j + 1; k < size; k++) {
				    if (array[i] + array[j] + array[k] < sum) {
					    count++;
					    System.out.print(count + ": ");
					    System.out.print(array[i] + ",");
					    System.out.print(array[j] + ",");
					    System.out.println(array[k]);
				    }
			    }
			}
		}
	    System.out.print("Number of Triplets = " + count);
    }

}




/*
run:
 
1: 4,5,1
2: 4,2,1
3: 4,2,3
4: 4,1,3
5: 5,2,1
6: 5,2,3
7: 5,1,3
8: 2,1,3
9: 2,1,7
Number of Triplets = 9
 
*/

 



answered Sep 16, 2022 by avibootz
...