Finding all subsets of a set (sentence) using C #

How can I find all subsets of a set using C #? here set is a sentence (string). For example: s = "i am nik"; What will be the code for this?

here the subsets of s are → i, am, nik, i am, i nik, am nik, i am nik.

+3
source share
2 answers

Here's the function I wrote to find all the unauthorized subsets from a given array.

List<T[]> CreateSubsets<T>(T[] originalArray)
{
    List<T[]> subsets = new List<T[]>();

    for (int i = 0; i < originalArray.Length; i++)
    {
        int subsetCount = subsets.Count;
        subsets.Add(new T[] { originalArray[i] });

        for (int j = 0; j < subsetCount; j++)
        {
            T[] newSubset = new T[subsets[j].Length + 1];
            subsets[j].CopyTo(newSubset, 0);
            newSubset[newSubset.Length - 1] = originalArray[i];
            subsets.Add(newSubset);
        }
    }

    return subsets;
}

So, given a integer array of 1,2,3,4,5, it will return a List<int[]>containing 31 subsets.

:. 6 , , string.Split('') . :

string originalString = "i am nik";
List<string[]> subsets = CreateSubsets(originalString.Split(' '));

foreach (string[] subset in subsets)
{
    Console.WriteLine(string.Join("\t", subset));
}
+6
    // all subsets of given set 
    static void numbcomb (string [] list) 
    {            
        int gelen = (int)Math.Pow(2,list.Length); // number of subsets (2^n)
        string [] result = new string [gelen]; // array with subsets as elements

        for(int i=0; i<gelen; i++) // filling "result"
        {
            for(int j=0;j<list.Length;j++)  // 0,1,2 (for n=3)
            {
                int t = (int)Math.Pow(2, j); // 1,2,4 (for n=3)
                if ((i&t)!=0)  // the MAIN THING in the program
                               // i can be:
                               // 000,001,010,011,100,101,110,111
                               // t can be: 001,010,100
                               // take a pensil and think about!
                { result[i]+=list[j]+" ";} // add to subset
            }
            Console.Write("{0}: ",i);// write subset number
            Console.WriteLine(result[i]);//write subset itself
        }
    }
+1

Source: https://habr.com/ru/post/1741386/


All Articles