How to count the triangles that can be formed using three different elements of an array in Java

1 Answer

0 votes
public class MyClass {
    private static int GetNumberOfTriangles(int[] arr) {
    	int size = arr.length;
    	int count = 0;
    
    	for (int i = 0; i < size; i++) {
    		for (int j = i + 1; j < size; j++) {
    			for (int k = j + 1; k < size; k++) { 
    			    // triangle = sum of two sides > value of the third side
    				if (arr[i] + arr[j] > arr[k] && 
    				    arr[i] + arr[k] > arr[j] && 
    				    arr[k] + arr[j] > arr[i]) {
    					System.out.println(arr[i] + " " + arr[j] + " " + arr[k]);
    					count++;
    				}
    			}
    		}
    	}
    	return count;
    }
    public static void main(String args[]) {
      	int[] arr = {2, 3, 4, 5, 6, 7};

	    System.out.print(GetNumberOfTriangles(arr));
    }
}





/*
run:
 
2 3 4
2 4 5
2 5 6
2 6 7
3 4 5
3 4 6
3 5 6
3 5 7
3 6 7
4 5 6
4 5 7
4 6 7
5 6 7
13
 
*/

 



answered Sep 12, 2022 by avibootz
...