views:

73

answers:

1

is there a way to dynamically add this whole adding process instead of the manually entering the values like a.Add("1 & 2"); and so on by the way, this only happens if i select 5 conditions -i am doing the adding base on the maximum condition i cater which is 5

the subsets that i show below must be in that pattern although its ok that the order can be different but the values must be increment like (1 & 2 & 3).So jumping values like (1 & 4) is not allowed and no reverse subsets like (3 & 2)

ArrayList a = new ArrayList();
    a.Add("1 & 2");
    a.Add("2 & 3");
    a.Add("3 & 4");
    a.Add("4 & 5");
    a.Add("1 & 2 & 3");
    a.Add("2 & 3 & 4");
    a.Add("3 & 4 & 5");
    a.Add("1 & 2 & 3 & 4");
    a.Add("2 & 3 & 4 & 5");

So if i have 6 condition then the list will add on for type two subsets(5 & 6), type 3 subsets(4 & 5 & 6), ...goes on which will even create another type of subsets if possible which would be type 5(1 & 2 & 3 & 4 & 5) in this case

Any method/ways are welcome as long as the results are the same which is the arraylist will contain the whole set of subsets base on the maximum condition.

Cheers, Jaf

+2  A: 

It sounds like you might want the power set (the set of all subsets of some given set), but from your example, it looks like you want to enumerate all sub-lists in a list using a sliding window.

If you want the power set:

Example code for generating power sets is available in this answer to a similar question.

If you want sliding window sub-lists:

You could do something like this with the code below. The example prints out exactly what you have above (using a sliding window size from 2 to 5 over the set {1, 2, 3, 4, 5}).

Note: For clarity's sake, there is no bounds-checking or error handling in the code below. There should absolutely be some.

class Program
{
    static void Main(string[] args)
    {
        foreach (var list in SlidingWindow<int>.Generate(new int[] { 1, 2, 3, 4, 5 }, 2, 5))
        {
            Console.WriteLine(string.Join(" & ", list));
        }
    }
}

static class SlidingWindow<T>
{
    static public IEnumerable<IEnumerable<T>> Generate(ICollection<T> items, int minWindowSize, int maxWindowSize)
    {
        for (int i = minWindowSize; i < maxWindowSize; ++i)
        {
            foreach (var list in Generate(items, i))
                yield return list;
        }
    }

    static public IEnumerable<IEnumerable<T>> Generate(ICollection<T> items, int windowSize)
    {
        for (int i = 0; i < (items.Count - windowSize + 1); ++i)
            yield return items.Skip(i).Take(windowSize);
    }
}
Chris Schmich