Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding all subsets of a set(sentence) using c#

Tags:

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 that?

here the subsets of s will be-> i, am, nik, i am, i nik, am nik, i am nik.

like image 715
NikRED Avatar asked Feb 27 '23 04:02

NikRED


2 Answers

Here's a function I wrote to find all incontiguous 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 an integer array of 1,2,3,4,5, it will return a List<int[]> containing 31 subsets.

Edit: Based upon your update, you can generate the 6 subsets you need with the function above and by using string.Split(' ') on your original sentence. Consider:

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

foreach (string[] subset in subsets)
{
    Console.WriteLine(string.Join("\t", subset));
}
like image 62
Anthony Pegram Avatar answered Mar 12 '23 02:03

Anthony Pegram


    // 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
        }
    }
like image 27
Orlovnikt Avatar answered Mar 12 '23 03:03

Orlovnikt