Skip to content

Add possible combinations of r elements in a given array

Ashish Sahu

Ashish Sahu

Asked Aug 7, 2015, 6:36 AM EDT1 answer
Share
LinkedInX
Hi Experts,
 
Add  all possible combinations of r elements in a given array of size n

Example: is input array     
int[] arr = new int[] { 1, 2, 3, 4, 5,6 };
output:  possible combination of arrary below:
1+4+5=10
2+3+5 =10
1+2+3+4=10
6+4=10
6+1+3=10

please help me

Thanks & Regards
Ashish Kumar Sahu 

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Ashish Sahu
    0
    Java
     class Arrary2
        {
            static int Main()
            {
                //Console.WriteLine("Give the input of Arrary Length");
                //int arrLength = Convert.ToInt32(Console.ReadLine());
                //Console.WriteLine("Give the input of Arrary");
                //int[] arr = new int[arrLength];
                //for (int i = 0; i < arr.Length; i++)
                //{
                //    arr[i] = Convert.ToInt32(Console.Read());
                //}
                int[] arr = new int[] { 1, 2, 3, 4, 5 };
                //int[] arr = new int[] { 2, 5, 6, 8, 4, 3, 1 };
                //int[] arr = new int[] { 8, 5, 6, 2, 4, 3, 1 };
                //Console.WriteLine("Give the input of combination of number");
                //int r = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Possible Combination Are Given Below======>");
                int n = arr.Length;
                for (int r = 2; r < arr.Length; r++)
                {
                    printCombination(arr, n, r);
                }
                Console.ReadKey();
                return 0;
            }
    
            static void printCombination(int[] arr, int n, int r)
            {
                int[] data = new int[r];
    
                combinationUtil(arr, n, r, 0, data, 0);
            }
    
            static void combinationUtil(int[] arr, int n, int r, int index, int[] data, int i)
            {
                int sum = 0;
                if (index == r)
                {
                    for (int j = 0; j < r; j++)
                    {
                        //Console.Write(data[j]);
                        sum = sum + data[j];
                    }
                    if (sum == 10)
                    {
                        for (int j = 0; j < r; j++)
                            Console.Write(data[j] + "+");
                        Console.Write("=====" + sum);
                        Console.WriteLine();
                    }
                    //Console.WriteLine();
                    return;
                }
                if (i >= n)
                    return;
                data[index] = arr[i];
                combinationUtil(arr, n, r, index + 1, data, i + 1);
                combinationUtil(arr, n, r, index, data, i + 1);
            }
        }
    0