tags:

views:

163

answers:

3

I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that.

ie.

50 + 100 = 150

int.Max + 50 = int.Max and not int.Min + 50

+4  A: 
int penaltySum(int a, int b)
{
    return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}

Update: If your penalties can be negative, this would be more appropriate:

int penaltySum(int a, int b)
{
    if (a > 0 && b > 0)
    {
        return (int.MaxValue - a < b) ? int.MaxValue : a + b;
    }

    if (a < 0 && b < 0)
    {
        return (int.MinValue - a > b) ? int.MinValue : a + b;
    }

    return a + b;
}
Derek Park
+6  A: 

This answer...

int penaltySum(int a, int b)
{
    return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}

fails the following test:

[TestMethod]
public void PenaltySumTest()
{
    int x = -200000; 
    int y = 200000; 
    int z = 0;

    Assert.AreEqual(z, penaltySum(x, y));
}

I would suggest implementing penaltySum() as follows:

private int penaltySum(int x, int y, int max)
{
    long result = (long) x + y;
    return result > max ? max : (int) result;
}

Notice I'm passing in the max value, but you could hardcode in the int.MaxValue if you would like.

Alternatively, you could force the arithmetic operation overflow check and do the following:

private int penaltySum(int x, int y, int max)
{
   int result = int.MaxValue;

   checked
   {
       try
       {
           result = x + y;
       }
       catch
       {
           // Arithmetic operation resulted in an overflow.
       }
   }

   return result;

}

Ben Griswold
Thanks for pointing out my oversight. I've updated my example to include an option for negative penalties.
Derek Park
As for your options, both work, but I still think the method I provided is superior. Your first technique isn't general, as it requires that a larger type be available. Your second technique uses exceptions, so I don't believe it meets the "efficiency" requirement Tomas specified.
Derek Park
A: 

Does it overflow a lot, or is that an error condition? How about using try/catch (overflow exception)?

GregUzelac