Monday, December 30, 2013

Triplets

Triplets are a set of three similar things.
Complete the function to print all the triplets such that A+B = C 
public static void PrintTriplets(int[ ] data) 
{ 
    //write code here
}
Input & Output
UTC
Sample Input
Sample Output
01
data = {2,3,4,5,7}

<2,3,5>
<2,5,7>
<3,4,7>
02
array = {1,2,3,4,5,7,9}

<1,2,3>
<1,3,4>
<1,4,5>
<2,3,5>
<2,5,7>
<3,4,7>
<4,5,9>

SOLUTION: 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Triplets_DEP
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the length of array : ");
            int i = int.Parse(Console.ReadLine());
            int j = 0;

            int[] arr = new int[i];
            for (j = 0; j < i; j++)
            {
                Console.Write("arr[" + j + "]: ");
                arr[j] = int.Parse(Console.ReadLine());
            }

            //Sorting the array
            Boolean change = false;
            Int32 temp = 0;
            for (i = 0; i < arr.Length; i++)
            {
                for (j = 0; j < arr.Length - 1; j++)
                {
                    if (arr[j] > arr[j + 1])
                    {
                        change = true;
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
                if (!change)
                {
                    break;
                }
            }

            //Finding the triplets
            Console.WriteLine("Triplates ...\n----------------");
            int sum = 0;
            for (i = 0; i < arr.Length; i++)
            {
                for (j = i + 1; j < arr.Length; j++)
                {
                    sum = arr[i] + arr[j];
                    for (int k = j + 1; k < arr.Length; k++)
                    {
                        if (sum == arr[k])
                        {
                            Console.WriteLine(arr[i] + " " + arr[j] + " " + arr[k]);
                        }
                    }
                }
            }
        }
    }
}

No comments:

Post a Comment