找到总数的数字

时间:2018-01-20 06:07:43

标签: c# data-structures

我在数组中有65个数字 例如:[1,2,3,4,5 ..... 65]。我在另一个变量中有一个值。例如:10。我想找到我必须从数组中求和的数字,以便在变量中获得该数字。在这个例子中它是2 + 3 + 5 = 10.是否有任何伪代码或任何c#代码可用于此?

此致 乔

1 个答案:

答案 0 :(得分:0)

我为你准备了一个小课程。我希望,这有助于:)

这是程序:

var finder = new NumbersForTotalFinder(Enumerable.Range(1, 65));
var results = finder.Find(10);
Debug.Assert(results.All(a => a.Sum() == 10));

这里有发现者

class NumbersForTotalFinder
{
    public NumbersForTotalFinder(IEnumerable<int> numbers)
    {
        _numbers = numbers.OrderBy(n => n).ToArray();
    }

    public List<int[]> Find(int total)
    {
        var results = new List<int[]>();
        var temp = new int[_numbers.Length];

        for (var index = 0; index < _numbers.Length; index++)
        {
            var num = _numbers[index];
            temp[0] = num;
            if (num == total)
            {
                SaveResult(results, temp, 1);
            }
            if (num >= total)
            {
                break;
            }
            Check(index + 1, 1, num, total, results, temp);
        }

        return results;
    }

    private void Check(int index, int depth, int sum, int total, List<int[]> results, int[] temp)
    {
        while (index < _numbers.Length)
        {
            var newNum = _numbers[index];
            var newSum = sum + newNum;

            if (newSum > total)
            {
                break;
            }

            temp[depth] = newNum;
            if (newSum == total)
            {
                SaveResult(results, temp, depth + 1);
                break;
            }

            Check(index + 1, depth + 1, newSum, total, results, temp);
            index++;
        }
    }

    private void SaveResult(List<int[]> results, int[] temp, int length)
    {
        var newResult = new int[length];
        Array.Copy(temp, newResult, length);
        results.Add(newResult);
    }

    private int[] _numbers;
}