Printing all the
possible combinations of a set of elements
using System;
using
System.Collections;
using
System.Linq;
using
System.Text;
namespace
ConsoleApplication3
{
class Program
{
static int count = 0;//Variable
which counts the number of combinations printed.
static void Main(string[]
args)
{
ArrayList
list = new ArrayList();
string
input = "abcde";
char[]
arr = new char[input.Length];
arr = input.ToCharArray();
//int[]
arr = { 1, 2, 3, 4, 5 };
combine(arr,list,0);
Console.WriteLine("The total number of combinations is: "
+ count);
}
//Change
char[]arr to int[]arr to use the function for an int array.
static void combine(char[]
arr, ArrayList list, int index)
{
if
(index == arr.Length)
{
return;
}
else
{
while
(index < arr.Length)
{
list.Add(arr[index]);
//Printing
format
Console.Write("{");
for
(int i = 0; i < list.Count; i++)
{
if (i !=
list.Count - 1)
{
Console.Write(list[i] + ",");
}
else
{
Console.Write(list[i]);
}
}
Console.Write("}");
Console.WriteLine();
//Printing
format.
count++;
combine(arr, list, index +
1);
//Removing
the last element of the present list on returning.
list.RemoveAt(list.Count -
1);
index++;
}
}
}
}
}
thank u for sharing this post Meraki Firewall
ReplyDeleteMeraki Cloud