Lets say I have a small integer array like this:
{10,20,30}
Now for the items of that array I want to apply the following formula:
10^(arrayLenght-1) + 20^{arrayLenght-2) + 30^{arrayLenght-3}
Is there a way to accompish this by using the linq aggregate methode though you need some kind of an iterator, which aggregate doesnt implement when I see this right?
Try this:
var a = new int[]{10, 20, 30};
int i = 0;
a.Sum(x => Math.Pow(x, a.Length - ++i));
It uses Sum
method because it's more accurate here.
also you can use:
var a = new int[]{10, 20, 30};
a.Select((x,i)=> Math.Pow(x,a.Length-(i+1)));
Here's how I would do it:
array.Select((num, index) => Math.Pow(num, items.Length - index - 1)).Sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With