Need algorithm for creating all unique combinations

Do it like this:

    private static void GetCombination(ref List<string[]> list, string[] t, int n, int m, int[] b, int M)
    {
        for (int i = n; i >= m; i--)
        {
            b[m - 1] = i - 1;
            if (m > 1)
            {
                GetCombination(ref list, t, i - 1, m - 1, b, M);
            }
            else
            {
                if (list == null)
                {
                    list = new List<string[]>();
                }
                string[] temp = new string[M];
                for (int j = 0; j < b.Length; j++)
                {
                    temp[j] = t[b[j]] + " ";
                }
                list.Add(temp);
            }
        }
    }

    public static List<string[]> GetCombination(string[] t, int n)
    {
        if (t.Length < n)
        {
            return null;
        }
        int[] temp = new int[n];
        List<string[]> list = new List<string[]>();
        GetCombination(ref list, t, t.Length, n, temp, n);
        return list;
    }

How to use:

List<string[]> output = new List<string[]>();

string alpha = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] input = alpha.Split(',').ToArray();

output = GetCombination(input, 16);

You will receive 5311735 combination, so you maybe run into a “OutOfMemoryException”.
I would recommend to use a database if you really have to handle so much data.

Leave a Comment