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

1 Answer

0 votes
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int[] array = new int[] {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++;
						Console.Write(count + ": ");
						Console.Write(array[i] + ",");
						Console.Write(array[j] + ",");
						Console.WriteLine(array[k]);
					}
				}
			}
		}
		Console.Write("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
...