如何在c#中执行组合任务



我有一个组合任务的问题。我想有一个代码,可以处理这个数学计算48/5 = 1712304 (5!= 5*4*3*2*1 = 120 48*47*46*45*44 = 205476480 205476480/120 = 1712304)

这里有更多的细节。我有一个包含48个字符串的字符串数组。字符串的长度在2到3个字符之间。

string array[] = new string[]{"A1","1D","410" /*[....]*/}

我想把5个字符串组合在一起,我想用整个数组来做这件事,我最大的问题是,一个组合的字符串只允许包括48个字符串中的每一个。并且每个组合字符串必须是唯一的

最后,我需要一个包含1712304个字符串条目的列表,长度必须在10到15位之间。例如,一个字符串可能看起来像这样"A11A4103E1T"。

回到数学,我知道有1712304个组合选项,所以任何其他结果一定是错误的。这就是我的问题所在。

我创建了以下代码,但没有成功的结果

        string[] siDigit = new string[iNumDigits];
        List<string> liste = new List<string>();
        const int iDigitBase = 48;
        const int iNumDigits = 5;
        for (int i = 0; i < 1712303; ++i)
        {
            int i2 = i;
            for (int i3 = 0; i3 < iNumDigits; ++i3)
            {
                siDigit[i3] = array[i2 % iDigitBase];
                i2 /= iDigitBase;
            }
            bool duplicate_free = siDigit.Distinct().Count() == siDigit.Length;
            if (duplicate_free == true)
            {
                liste.Add(siDigit[0] + siDigit[1] + siDigit[2] + siDigit[3] + siDigit[4]);
                Console.Write(siDigit[0] + siDigit[1] + siDigit[2] + siDigit[3] + siDigit[4]);
                Console.WriteLine();
            }
        }

我得到的是在我的列表中减少条目的方法,我只得到1317051个条目,不知道为什么。我找不到解决这个问题的方法,希望有人能帮我解决。

任何帮助都将是非常感激的。

p。在德国,他们教的英语并不好。

我认为你的算法是错误的。

考虑i = 0, i2 = 0,所以siDigit[i3](i3 = 0,1,2,3,4)是array[0], duplicate_free为false。你失去了一个。因此,您无法获得所有条目。

这是一个递归算法:

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;
}

最新更新