Reputation: 1
As a part of a LINQ tutorial I have the following exersise:
You're required to calculate the value of an nth-degree polynomial. The arguments of the function are:
-int x - the value of x for the polynomial
-IEnumerable coeffs - the polynomial coefficients
Example:
-Input: 2, [3,4,5]
-Output: 25 (calculated as
3*2^2+4*2+5
)Hint: you may need the overload of Aggregate() that takes a seed value. You may also need to introduce a separate variable for tracking the index of the element you're processing.
Any ideas?
Thank you so much!
Upvotes: 0
Views: 630
Reputation: 11
As simple as that:
public static int Poly(int x, IEnumerable<int> coeffs)
{
int idx = 0;
return coeffs.Reverse().Aggregate(0, (p, q) => p + q * (int)Math.Pow(x, idx++));
}
Upvotes: 1
Reputation: 1876
First of all weird choice of IEnumerable coefficients. You could rewrite the below code to "subtract" rather than add to the current coefficient's rank, I guess that's what is expected by whoever designed the problem, since that would require using the overload which takes a seed value, since the first term's value would no longer be coefficient * x^0 (or simply coefficient) in that case. I just think this version is easier to follow and explain, and you should try writing the answer as expected based on this:
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;
});
Upvotes: 0