用谓词求解完美和

问题描述 投票:0回答:1

大家好我正在尝试解决此 c# 练习,但我找不到解决方法。即使不使用下面建议的提示。

用下面的例子做一个完美的总结

例一:

输入1:5 输入 2:{9,6,3,12,7} 输入 3:14

输出:1

说明:

这里,元素7+7的和=14。因此,完美和的数量 给定的数组是 1。因此,1 作为输出返回。

例二:

输入 1:5 输入 2:(4、7、8、2、3} 输入 3:12

输出:2

说明:

这里,元素8+4=12,7+3+2=12的和。因此,数量 给定数组中的完美和为 2。因此,返回 2 作为 输出

提示: 我更喜欢在函数签名中看到谓词。它说明传递的方法做出决定,而不仅仅是返回成功代码或不同类型的布尔值。

基本代码:

class Program
{
    static void Main(string[] args)
    {
        //Call the method here
        Console.ReadKey();
    }

    static int PerfectSums(int input, int[] input2, int input3)
    {
        throw new NotImplementedException();
    }
}
c# logic predicate
1个回答
0
投票

已经解决了

static int PerfectSums(int input, int[] input2, int input3)
{
    int count = 0;

    // Loop through each element in the array
    for (int i = 0; i < input; i++)
    {
        int remainingSum = input3 - input2[i];

        // Check if there exists another element in the array whose value equals to the remaining sum
        if (Array.Exists(input2, x => x == remainingSum))
        {
            count++;
        }
    }

    return count;
}
© www.soinside.com 2019 - 2024. All rights reserved.