John Smith
John Smith

Reputation: 12266

Counting numbers within a range

Say I have two (positive) arbitrary decimal numbers, a and b.

I want to be able to count the number of integers that exist between a and b (a less than or equal to [Valid Integers] which is less than b) such that none of them exceed arbitrary number L. Is there an easy way to do this? I've tried loops and floors/ceilings but none of it is working the way I want it to and it's just getting to be messy.

Upvotes: 1

Views: 248

Answers (1)

Matt Mitchell
Matt Mitchell

Reputation: 41871

The simple case is:

Count = Math.Min(Math.Max(a, b), L) - Math.Min(a,b);

However that has issues when L is less than both a and b, and doesn't cater for decimal numbers.

As such, give this a go:

int Count(double firstInput, double secondInput, double limit = int.MaxValue)
{
    int minInput = (int)Math.Ceiling(Math.Min(firstInput, secondInput));
    int maxInput = (int)Math.Floor(Math.Max(firstInput, secondInput));

    int L = (int)Math.Floor(limit);

    if (L<minInput)
        return 0;

    bool maxInputHasDecimals = (maxInput != Math.Max(firstInput, secondInput));
    return Math.Min(maxInput, L) - minInput + (maxInputHasDecimals ? 1 : 0);
}

Count(56.67, 67.8); // 11
Count(56.67, 67.8, 62.0); // 6
Count(56.67, 67.8, -3); // 0
Count(-10, -5, -3); // 5
Count(-10, -5, -7); // 3
Count(56.67, 67.0); // 10

Upvotes: 1

Related Questions