How to count the number of possible triangles from a given array in C#

1 Answer

0 votes
using System;

// Triangle = the sum of any two values (sides) > than the third value (third side)

// A + B > C
// B + C > A
// C + A > B

public class Program
{
	private static int CountTriangles(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++) {
					if (arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) {
						count++;
						Console.Write(arr[i] + " + " + arr[j] + " > " + arr[k] + " | ");
						Console.Write(arr[i] + " + " + arr[k] + " > " + arr[j] + " | ");
						Console.WriteLine(arr[k] + " + " + arr[j] + " > " + arr[i]);
					}
				}
			}
		}
		return count;
	}
	public static void Main(string[] args)
	{
		int[] arr = new int[] {120, 80, 13, 16, 9, 14, 19};


		int total_triangles = CountTriangles(arr);

		Console.Write("Total triangles : " + total_triangles);
	}
}






/*
run:
  
13 + 16 > 9 | 13 + 9 > 16 | 9 + 16 > 13
13 + 16 > 14 | 13 + 14 > 16 | 14 + 16 > 13
13 + 16 > 19 | 13 + 19 > 16 | 19 + 16 > 13
13 + 9 > 14 | 13 + 14 > 9 | 14 + 9 > 13
13 + 9 > 19 | 13 + 19 > 9 | 19 + 9 > 13
13 + 14 > 19 | 13 + 19 > 14 | 19 + 14 > 13
16 + 9 > 14 | 16 + 14 > 9 | 14 + 9 > 16
16 + 9 > 19 | 16 + 19 > 9 | 19 + 9 > 16
16 + 14 > 19 | 16 + 19 > 14 | 19 + 14 > 16
9 + 14 > 19 | 9 + 19 > 14 | 19 + 14 > 9
Total triangles : 10
  
*/

 



answered Apr 14, 2023 by avibootz
...