Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator in aggregate (linq)?

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?

like image 811
Christoph Avatar asked Dec 01 '22 20:12

Christoph


2 Answers

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)));
like image 29
Kamil Budziewski Avatar answered Dec 03 '22 09:12

Kamil Budziewski


Here's how I would do it:

array.Select((num, index) => Math.Pow(num, items.Length - index - 1)).Sum();
like image 184
Magnus Grindal Bakken Avatar answered Dec 03 '22 09:12

Magnus Grindal Bakken