Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of Exceedence in a series

Tags:

c#

linq

I have a series data in IEnumrable<double>.

Let the dummy data be:

0
0
0
1
1.6
2.5
3.5
2.51
1.0
0
0
0
2.52
3.5
6.5
4.5
1.2
1.0
2.53
3.5

let my value of Exceedence be 1.5, so I want to count the number of time my value in series goes above 1.5 (basically number of times 1.5 constant line cut the graph). In above case it will be 3 ({1.6-2.51}, {2.52-4.5}, {2.53-3.5}).

I can do this by iterating through each member and keeping the count everytime it goes up or down the Exceedence value.

I am wondering is there any way to do this using LINQ query.

like image 740
Mohit Vashistha Avatar asked Apr 07 '11 10:04

Mohit Vashistha


2 Answers

Is that what you want?

        bool isAbove = false;
        int count = yourList.Count(x =>
        {
            if (x > 1.5 && !isAbove)
            {
                isAbove = true;
                return true;
            }
            else if (x < 1.5)
            {
                isAbove = false;
            }
            return false;
        });
like image 70
Stecya Avatar answered Oct 20 '22 23:10

Stecya


You could use this helper function that will give you all of the ranges above your limit

public IEnumerable<IEnumerable<double>> GetRangesAboveLimit(IEnumerable<double> source, double limit)
{
    //keep going until we've processed the entire range
    while (source.Any())
    {
        //skip elements below the limit
        source = source.SkipWhile(e => e <= limit);
        //yield the elements above the limit
        yield return source.TakeWhile(e => e > limit);
        //now skip those elements and then continue
        source = source.SkipWhile(e => e > limit);
    }
}

You'd then be able to use it like this:

var range = new double [] { /* initialise here */ };
var rangesAboveLimit = GetRangesAboveLimit(range, 1.5);

This would then allow you to not only get the count of how many ranges are above your limit (3) but also allow you to look at the values of those ranges.

The results for your specific example look like this:

enter image description here

like image 24
Doctor Jones Avatar answered Oct 20 '22 22:10

Doctor Jones