Printing all combinations using binary approach

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Runtime.InteropServices;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Printing all combinations/power set using binary approach
            char[] charArray = { 'a', 'b', 'c', 'd'};
            int maxLimit = (int)Math.Pow(2, charArray.Length) - 1;
            for (int i = 1; i <= maxLimit; i++)
            {
                string binary = DecimalToBinary(i).PadLeft(charArray.Length, '0');
                string combination = "";
                for (int j = 0; j < binary.Length; j++)
                {
                    if (binary[j] != '0')
                    {
                        combination = combination + charArray[j];
                    }
                }
                Console.WriteLine(combination);
            }
        }
        public static string DecimalToBinary(int num)
        {
            string rem = "";
            while (num >= 1)
            {
                int quot = num / 2;
                rem += (num % 2).ToString();
                num = quot;
            }
            // Reversing the  value
            string bin = "";
            for (int i = rem.Length - 1; i >= 0; i--)
            {
                bin = bin + rem[i];
            }
            return bin;
        }
    }
}
Output:
======================
d
c
cd
b
bd
bc
bcd
a
ad
ac
acd
ab
abd
abc
abcd
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s