tags:

views:

720

answers:

9

given an array: [dog, cat, mouse]

what the most elegant way to create:

[,,]
[,,mouse]
[,cat,]
[,cat,mouse]
[dog,,]
[dog,,mouse]
[dog,cat,]
[dog,cat,mouse]

I need this to work for any sized array.

This is essentially a binary counter, where array indices represent bits. This presumably lets me use some bitwise operation to count, but i can't see a nice way of translating this to array indices though.

Thanks

+2  A: 
static IEnumerable<IEnumerable<T>> GetSubsets<T>(IList<T> set)
{
    var state = new BitArray(set.Count);
    do
        yield return Enumerable.Range(0, state.Count)
                               .Select(i => state[i] ? set[i] : default(T));
    while (Increment(state));
}

static bool Increment(BitArray flags)
{
    int x = flags.Count - 1; 
    while (x >= 0 && flags[x]) flags[x--] = false ;
    if (x >= 0) flags[x] = true;
    return x >= 0;
}

Usage:

foreach(var strings in GetSubsets(new[] { "dog", "cat", "mouse" }))
    Console.WriteLine(string.Join(", ", strings.ToArray()));
Mehrdad Afshari
That's the answer I would write if I knew C#! But it still could be made nicer with a small change to how Increment works. I'll post it below, because it won't fit into comment.
ilya n.
I wrote the optimization below :)
ilya n.
+1  A: 
 string[] source = new string[] { "dog", "cat", "mouse" };
 for (int i = 0; i < Math.Pow(2, source.Length); i++)
 {
     string[] combination = new string[source.Length];
     for (int j = 0; j < source.Length; j++)
     {
         if ((i & (1 << (source.Length - j - 1))) != 0)
         {
             combination[j] = source[j];
         }
    }
    Console.WriteLine("[{0}, {1}, {2}]", combination[0], combination[1], combination[2]);
}
Michael
The question explicitly mentions: "given any sized array."
Mehrdad Afshari
care to generalise it, that was the point in my question :)
Andrew Bullock
Updated to a more generalized version.
Michael
Chose this as its concise and to the point, also probably more efficient than Linq or List<>s
Andrew Bullock
"Probably" in this instance being short for "I'm too lazy to measure it."
Kyralessa
A: 

There is some discussion and code on creating permutations here.

Oops, per comment. :)

JP Alioto
He is not looking for permutations; he is looking for subsets.
Jason
A: 

I'm not very familiar with C# but I'm sure there's something like:

// input: Array A
foreach S in AllSubsetsOf1ToN(A.Length): 
    print (S.toArray().map(lambda x |> A[x]));


Ok, I've been told the answer above won't work. If you value elegance over efficiency, I would try recursion, in my crappy pseudocode:

Array_Of_Sets subsets(Array a) 
{
    if (a.length == 0) 
         return [new Set();] // emptyset
    return subsets(a[1:]) + subsets(a[1:]) . map(lambda x |> x.add a[0]) 
}
ilya n.
No there's nothing like that in the .NET Framework BCL.
Mehrdad Afshari
Afraid not.
mquander
Unfortunately there is not.
Jason
+1  A: 

Here's an easy-to-follow solution along the lines of your conception:

private static void Test()
{
    string[] test = new string[3] { "dog", "cat", "mouse" };

    foreach (var x in Subsets(test))
        Console.WriteLine("[{0}]", string.Join(",", x));
}

public static IEnumerable<T[]> Subsets<T>(T[] source)
{
    int max = 1 << source.Length;
    for (int i = 0; i < max; i++)
    {
        T[] combination = new T[source.Length];

        for (int j = 0; j < source.Length; j++)
        {
            int tailIndex = source.Length - j - 1;
            combination[tailIndex] =
                ((i & (1 << j)) != 0) ? source[tailIndex] : default(T);
        }

        yield return combination;
    }
}
mquander
The || source.Length == 0 shouldn't really be there: subsets of empty set exist. If you erase that, it will correctly return empty set.
ilya n.
+5  A: 

You can use the BitArray class to easily access the bits in a number:

string[] animals = { "Dog", "Cat", "Mouse" };
List<string[]> result = new List<string[]>();
int cnt = 1 << animals.Length;
for (int i = 0; i < cnt; i++) {
   string[] item = new string[animals.Length];
   BitArray b = new BitArray(i);
   for (int j = 0; j < item.Length; j++) {
      item[j] = b[j] ? animals[j] : null;
   }
   result.Add(item);
}
Guffa
A: 

This is a small change to Mehrdad's solution above. Please upvote his answer.

static IEnumerable<T[]> GetSubsets<T>(T[] set) {
    bool[] state = new bool[set.Length+1];
    for (int x; !state[set.Length]; state[x] = true ) {
        yield return Enumerable.Range(0, state.Length)
                               .Where(i => state[i])
                               .Select(i => set[i])
                               .ToArray();
        for (x = 0; state[x]; state[x++] = false);
    }
}

or with pointers

static IEnumerable<T[]> GetSubsets<T>(T[] set) {
    bool[] state = new bool[set.Length+1];
    for (bool *x; !state[set.Length]; *x = true ) {
        yield return Enumerable.Range(0, state.Length)
                               .Where(i => state[i])
                               .Select(i => set[i])
                               .ToArray();
        for (x = state; *x; *x++ = false);
    }
}
ilya n.
+2  A: 

Elegant? Why not Linq it.

    public static IEnumerable<IEnumerable<T>> SubSetsOf<T>(IEnumerable<T> source)
    {
        if (!source.Any())
            return Enumerable.Repeat(Enumerable.Empty<T>(), 1);

        var element = source.Take(1);

        var haveNots = SubSetsOf(source.Skip(1));
        var haves = haveNots.Select(set => element.Concat(set));

        return haves.Concat(haveNots);
    }
David B
+1  A: 

Here's a solution similar to David B's method, but perhaps more suitable if it's really a requirement that you get back sets with the original number of elements (even if empty):.

static public List<List<T>> GetSubsets<T>(IEnumerable<T> originalList)
{
    if (originalList.Count() == 0)
        return new List<List<T>>() { new List<T>() };

    var setsFound = new List<List<T>>();
    foreach (var list in GetSubsets(originalList.Skip(1)))
    {                
        setsFound.Add(originalList.Take(1).Concat(list).ToList());
        setsFound.Add(new List<T>() { default(T) }.Concat(list).ToList());
    }
    return setsFound;
}

If you pass in a list of three strings, you'll get back eight lists with three elements each (but some elements will be null).

Kyralessa