Software zum Erstellen von Kombinationen

Auf der Suche nach Software zum Erstellen von Kombinationen.

wiki

Antworten (1)

Ich bin auf einen Link zum Erstellen von Kombinationen gestoßen.

wiki

In C#

static class Combinations
{
    // Enumerate all possible m-size combinations of [0, 1, ..., n-1] array
    // in lexicographic order (first [0, 1, 2, ..., m-1]).
    public static IEnumerable<int[]> CombinationsRosettaWoRecursion(int m, int n)
    {
        int[] result = new int[m];
        Stack<int> stack = new Stack<int>(m);
        stack.Push(0);
        while (stack.Count > 0)
        {
            int index = stack.Count - 1;
            int value = stack.Pop();
            //Debug.WriteLine($"stack.Pop() {value}   index {index}   stack.Count {stack.Count}");
            while (value < n)
            {
                //Debug.WriteLine($" result[{index}] = {value}");
                result[index++] = value++;
                stack.Push(value);
                if (index != m) continue;
                //Debug.WriteLine(String.Join(",", result));
                yield return result;
                break;
            }
        }
    }

    public static IEnumerable<T[]> CombinationsRosettaWoRecursion<T>(T[] array, int m)
    {
        if (array.Length < m)
            throw new ArgumentException("Array length can't be less than number of selected elements");
        if (m < 1)
            throw new ArgumentException("Number of selected elements can't be less than 1");
        T[] result = new T[m];
        foreach (int[] j in CombinationsRosettaWoRecursion(m, array.Length))
        {
            for (int i = 0; i < m; i++)
            {
                result[i] = array[j[i]];
            }
            yield return result;
        }
    }
}