问题描述
作为LINQ教程的一部分,我要进行以下练习:
您需要计算n次多项式的值。 该函数的参数为:
- int x -多项式的x值
- IEnumerable coeffs -多项式系数
示例:
-输入:2,[3、4、5]
-输出:25(计算为
3*2^2+4*2+5
)提示:您可能需要 Aggregate()的重载,该重载需要种子 值。您可能还需要引入一个单独的变量进行跟踪 您正在处理的元素的索引。
有什么想法吗?
非常感谢您!
解决方法
首先是IEnumerable系数的怪异选择。您可以重写下面的代码以“减去”而不是增加当前系数的排名,我想这是设计问题的人所期望的,因为这将需要使用带有种子值的重载,因为第一项的值将在这种情况下,不再是系数* x ^ 0(或简称为系数)。我只是认为此版本更易于理解和解释,因此您应该根据以下内容尝试编写答案:
IEnumerable<int> coefficients = new int[] { 3,4,5 }.Reverse(); //we reverse the coefficients' order for simplicity,in real cases this might not be possible,since IEnumerable does not guarantee it is "replayable"
int x = 2;
int rank = 1; //we start from rank 1 since the first value is x^0 * coefficient,so it's already "added" in Aggregate and correct,we don't need to use the "seed value overload"
var polynomialValue = coefficients.Aggregate((sofar,current) =>
{
//we just need to worry about calculating the current value
int currentValue = current * (int)Math.Pow(x,rank); //you could replace this with a for if you want or use Aggregate here as well,I was just lazy
Console.WriteLine($"Adding {current} * {x}^{rank} = {currentValue}");
rank++;
//and returning the aggregated result which is what we calculated so far plus the current term
return sofar + currentValue;
});