2

I want help with getting the subsets of an array in C#. All other examples could not help me much.

I want to get all the subsets of a particular size of an array.

for example if input array is {1,2,3,4} and i want all subsets of size 3, all the unique subsets {1,2,3},{1,2,4},{2,3,4},{1,3,4} must be returned.

I am new to C# and any kind of help is much appreciated.

Abhishek
  • 2,829
  • 3
  • 29
  • 56
  • http://stackoverflow.com/questions/13765699/how-can-i-obtain-all-the-possible-combination-of-a-subset – I4V Apr 16 '13 at 17:47
  • http://stackoverflow.com/questions/1952153/what-is-the-best-way-to-find-all-combinations-of-items-in-an-array – arunlalam Apr 16 '13 at 18:19

2 Answers2

0

Check this article. This is described in detail with examples in all sorts of programming languages. I don't feel the need to copy others solutions so I will leave this as a link for you to choose from the MANY examples which should help you

Algorithm to return all combinations of k elements from n

Community
  • 1
  • 1
Dave
  • 478
  • 2
  • 12
0

Sounds suspiciously like a homework assignment....

Since I presume the size is variable, you'll want to use recursion. Something like:

    static void Main(string[] args)
    {
        int[] originalList = new int[] { 1, 2, 3, 4 };
        Stack<int> currentList = new Stack<int>();
        List<int[]> listOfSubsets = new List<int[]>();

        BuildListOfSubsets(originalList, listOfSubsets, 3, 0, currentList);
    }

    private static void BuildListOfSubsets(int[] originalList, List<int[]> listOfSubsets, int sizeOfSubsetList, int currentLevel, Stack<int> currentList)
    {
        if (currentList.Count == sizeOfSubsetList)
        {
            int[] copy = new int[sizeOfSubsetList];
            currentList.CopyTo(copy, 0);
            listOfSubsets.Add(copy);
        }
        else
            for (int ix = currentLevel; ix < originalList.Length; ix++)
            {
                currentList.Push(originalList[ix]);
                BuildListOfSubsets(originalList, listOfSubsets, sizeOfSubsetList, ix + 1, currentList);
                currentList.Pop();
            }
    }

The result will be in the listOfSubsets list. See if you can find an optimization to leave the for loop early.

user1689571
  • 498
  • 1
  • 4
  • 16