C# 从整数列表中删除项目 int[] l = {1,2,3} - 或使用递归添加它们

C# remove item from list of integers int[] l = {1,2,3} - or use recursion to add them

因此,this 博客给出了每个软件工程师都应该能够在不到 1 小时内解决的五个编程问题,我只是重温了其中的一些概念。

第一题阅读

编写三个函数,使用 for 循环、while 循环和递归计算给定列表中数字的总和。

显然 for 和 while 循环很简单,但我从

开始
int[] l = { 1, 2, 3, 4, 5, 6, 7, 8, 9};

是否可以从列表中弹出一个项目,然后每次都通过缩短的列表?

我在 python 中看到的尝试:

numbers = [1,2,3,4,5,6,7,8,9]
def recurse_count(lst):
    if len(lst) == 1:
        return lst[0]
    else:
        i = len(lst) - 1
        subtotal = lst[i] + lst[i - 1]
        lst.pop() #into the void with you
        lst[-1] = subtotal
        return recurse_count(lst)

是否可以在 c# 中使用 int[]?

是的。我相信 List-class 有一个简单的 removeAt(int) 方法。递归方法如下所示:

public int sumThisUp(List<int> list) {
    int result = list[0];
    list.removeAt(0);
    return (list.length > 0) ? result + sumThisUp(list) : result;
}

或者,如果您不想编辑原始列表,可以这样做:

public int sumThisUp2(List<int> list, int index = 0) {
   int result = list[index++];
   return (list.Count > index) ? result + sumThisUp2(list, index) : result;
}

是的,在 C# 中是可能的。 但我想先介绍一些技巧:我们可以只传递起始索引而不是修改源列表。会快很多:

private static int Sum(int[] array, int startIndex)
{
    if (startIndex >= array.Length)
    {
        return 0;
    }
    return array[startIndex] + Sum(array, startIndex + 1);
}

static void Main(string[] args)
{
    int[] array = new int[] { 1, 2, 3, 4 };
    int result = Sum(array, 0);
    Console.WriteLine(result);
}

应该这样做:

public int Sum(int[] numbers, int startAt = 0)
{
    if (startAt == numbers.Length)
        return 0;
    return numbers[startAt] + Sum(numbers, startAt + 1);
}

一个非常优雅的解决方案是:

static public int sumThisUp(IEnumerable<int> list)
{
    return list.FirstOrDefault() + (list.Any() ? sumThisUp(list.Skip(1)) : 0);
}