簡體   English   中英

在列表中搜索數字,這些數字加起來等於C#中的總和

[英]Searching through a list for numbers adding up to a sum in C#

我讓用戶輸入一組介於1到19之間的數字...,需要找到盡可能多的數字,這些數字加起來等於40,每個數字只能使用一次。

可以這樣說:19、17、11、13、8、9、7、5、10、16、14、8、7、3。

然后輸出應為:
19、11、10
16,14,7,3
17、8、8、7

列表中還有13、9和5。

我找到了一些建議,但他們似乎只想尋找一場比賽,我自己嘗試了一下,但仍然缺乏改進。

    private void btnCalc_Click(object sender, RoutedEventArgs e)
    {
        // Copy the list to a new list:
        List<int> lookInto = new List<int>();
        foreach(int i in weaponList)
        {
            lookInto.Add(i);
        }

        int lookFor = 40;
        while (lookFor > 0)
        {
            lookFor = Search(lookInto, lookFor);
        }
        if (lookFor != -1)
        {
            listSell.Items.Add(answer);
        }
    }

    private int Search(List<int> hay, int needle)
    {
        int lowestValue = hay.Min();
        int highestValue = hay.Max();

        if (hay.BinarySearch(needle) > 0)
        {
            int index = hay.BinarySearch(needle);

            if (answer == "")
            {
                answer += hay[index].ToString();
                needle -= hay[index];
                hay.Remove(needle);
            }
            else
            {
                answer += ", " + hay[index].ToString();
                needle -= hay[index];
                hay.Remove(needle);
            }
        }

        if (needle - highestValue > lowestValue || needle - highestValue == 0)
        {
            if (answer == "")
            {
                answer += highestValue.ToString();
                needle -= highestValue;
                hay.Remove(highestValue);
            }
            else
            {
                answer += ", " + highestValue.ToString();
                needle -= highestValue;
                hay.Remove(highestValue);
            }
        }
        else
        {
            for (int i = 0; i > hay.Count; i++)
            {
                if (needle - hay[i] == 0 || needle - hay[i] > lowestValue)
                {
                    if (answer == "")
                    {
                        answer += hay[i].ToString();
                        needle -= hay[i];
                        hay.RemoveAt(i);
                    }
                    else
                    {
                        answer += ", " + hay[i].ToString();
                        needle -= hay[i];
                        hay.RemoveAt(i);
                    }
                }
            }
            if (needle > 0)
            {
                needle = -1;
            }
        }

        return needle;
    }

我即將離開,無法鍵入實際的代碼塊,但是您可以按照以下方法進行操作:創建所有數字的鏡像靜態數組,使用遞歸函數逐步執行並嘗試從該數組中添加數字直到達到40,如果它們超過40,它只會返回-1,否則,所有用於達到40的索引都會在每次返回一組索引時從鏡像數組中刪除這些數字,因此下一個迭代將不會嘗試使用它們並將數字添加到集合列表中。 當遞歸函數停止時,您在主數組中剩下的就是未使用的數字,並且集合列表將包含所有找到的集合。

我希望這有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM