Introduction
In this article, we will be discussing an algorithm that returns possible (no. of pairs) digit pairs that are equal to a given number (6) using Tuple class.
Prerequisite
Suppose we pass a list of numbers List<int> { 1 , 2 , 3 , 4 , 5 , 6 } with 6 as a sum, The possible pairs should be :
- 0 0 3 ( 1 + 1 + 4 ) = 6
- 0 1 2 ( 1 + 2 + 3 ) = 6
- 0 2 1 ( 1 + 3 + 2 ) = 6
- 0 3 0 ( 1 + 4 + 1 ) = 6
- 1 0 2 ( 2 + 1 + 3 ) = 6
- 1 1 1 ( 2 + 2 + 2 ) = 6
- 1 2 0 ( 2 + 3 + 1 ) = 6
- 2 0 1 ( 3 + 1 + 2 ) = 6
- 2 1 0 ( 3 + 2 + 1 ) = 6
- 3 0 0 ( 4 + 1 + 1 ) = 6
How?
- The following is the basic function which we will implement in this article.
- public static List<Tuple<int,int,int>> PairsOfThreeDigitSum(IList<int> lstInt, int sum)
- {
-
- }
- The above function which is the return wist of Tuple<int,int,int> actually will contain three-digit pairs that are equal to a given sum.
- We will iterate through for loop and check if the sum of the list is equal to the sum we gave.
- for (int i=0;i<lstInt.Count;i++)
- {
- for (int i=0;i<lstInt.Count;i++)
- {
- for (int i=0;i<lstInt.Count;i++)
- {
- if (sum == (lstInt[i] + lstInt[j] + lstInt[k]))
- {
- pairs.Add(Tuple.Create<int,int,int>>(I , j, k);
- }
- }
- }
- }
- If condition becomes true it means this is the pair in which sum is equal to the sum we gave. I will store that pair index into our List of Tuples by Add() method
- if (sum == (lstInt[i] + lstInt[j] + lstInt[k]))
- {
- pairs.Add(Tuple.Create<int,int,int>>(I , j, k);
- }
- Loop iterates until the count of elements in the list; and finally, it will return the pairs which hold three digits pairs as with,
- Below is the function which will do the same.
Final Code
Below are the code and output window.
- class Program
- {
- static void Main(string[] args)
- {
- var lst = new List<int> { 1, 2, 3, 4, 5 };
- int sum = 6;
-
- List<Tuple< int, int, int >> pairs = PairsOfThreeDigitSum(lst, sum);
-
- Console.WriteLine("Possible pairs of three digits whose sum are equivalent to {0} ", sum);
-
- foreach (var _pairs in pairs)
- {
- Console.WriteLine("{0} {1} {2}", _pairs.Item1, _pairs.Item2, _pairs.Item3);
- }
-
- Console.ReadKey(true);
- }
-
- public static List<Tuple<int,int,int>> airsOfThreeDigitSum(IList<int> lstInt, int sum)
- {
- List<Tuple<int,int,int>> pairs = new List<Tuple<int,int,int>>();
- for (int i=0;i<lstInt.Count;i++)
- {
- for (int i=0;i<lstInt.Count;i++)
- {
- for (int i=0;i<lstInt.Count;i++)
- {
- if (sum == (lstInt[i] + lstInt[j] + lstInt[k]))
- {
- pairs.Add(Tuple.Create<int,int,int>>(I , j, k);
- }
- }
- }
- }
- return pairs;
- }
- }
Output
Summary
In this article, I discussed how we can create a method that returns Three-Digit Pairs using Tuple class in C#.
I hope you liked my article.:)