Iterator in aggregate (linq)?
Asked Answered
T

4

5

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?

Tight answered 23/8, 2013 at 11:54 Comment(3)
Where are the elements in the array supposed to be used in the formula? It would help if you showed how to do what you want with a for-loopHerstein
In C#, ^ is XOR, this will affect your return valueEnumerate
^ is supposed to be a power operator here. sry for the confusionTight
T
16

Here's how I would do it:

array.Select((num, index) => Math.Pow(num, items.Length - index - 1)).Sum();
Tirpitz answered 23/8, 2013 at 12:0 Comment(0)
A
4

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)));
Arabist answered 23/8, 2013 at 11:58 Comment(0)
C
0

You might try summing the results of a select instead of using aggregate

result = values.Select((t, index) => Math.Pow(t, (values.Length - (index + 1)))).Sum();
Caladium answered 23/8, 2013 at 12:7 Comment(3)
index starts with 0.Clime
@Enumerate Yes. Which is what was asked for in the original posting.Caladium
@Corak. Yep. may bad. EditingCaladium
R
0

The given answers are best to solve this problem, however if you need an aggregate function that exposes the iteration index, you can write your own.

public static TAccumulate Aggregate<TSource, TAccumulate>(
    this IEnumerable<TSource> source,
    TAccumulate seed,
    Func<TAccumulate, TSource, int, TAccumulate> func)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    if (func == null)
        throw new ArgumentNullException(nameof(func));

    var accumulate = seed;
    var i = 0;
    foreach (var item in source)
    {
        accumulate = func(accumulate, item, i);
        i++;
    }
    return accumulate;
}

Reverberator answered 9/12, 2023 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.