Thursday, June 20, 2013

Print all possible combinations of r elements in a given array of size n (C#)

For this question, I have taken an array of size 5 and printed all combinations of length 3. I used Linq query for doing this.

Solution


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Excercises
{
    class Program
    {
        static void Main(string[] args)
        {
            //To generate all the length-3 combinations of integers from the set {1, 2, 3, 4, 5}:
            int[] Arr = { 1, 2, 3, 4, 5 };
                var combo = from a in Arr
                            from b in Arr
                            from c in Arr
                            select string.Concat(a,b,c);
            foreach (var v in combo)
            {
            Console.WriteLine(v);
            }
            Console.ReadKey();
        }

    }
}

No comments: