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
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
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;
}
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;
}
Does it overflow a lot, or is that an error condition? How about using try/catch (overflow exception)?