Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# minimum of two numbers if one or both is greater than 0

Tags:

c#

The logic I'm looking for is if either of the numbers are >= 0 (which they don't have to be), then return the minimum of the two that is also greater than 0. The code I've written for it is so ugly that I'm ashamed to post it!

EDIT: Samples 1, -1 => 1 5,6 => 5 -1,-1 => 0

(if both are less than 0, return 0)

like image 546
probably at the beach Avatar asked Aug 22 '11 17:08

probably at the beach


1 Answers

I'm going to try my psychic powers, and assuming that if both are zero, you want to return 0.

In other words:

return x < 0 && y < 0 ? 0
     : x < 0 ? y
     : y < 0 ? x
     : Math.Min(x, y);

I'm sure I can do better though...

If they're not both greater than 0, then at least one will be less than zero, so you just care about the greater of them, or 0 if they're both less than zero. Otherwise, we just take the minimum.

return x < 0 || y < 0 ? Math.Max(Math.Max(x, y), 0) : Math.Min(x, y);

If you don't care much about performance, you could use:

new[] { x, y }.Where(z => z > 0)
              .DefaultIfEmpty() // Make sure there's at least one entry
              .Min();

Frankly none of these are terribly nice, IMO. I'd want a comment with any of them...

like image 76
Jon Skeet Avatar answered Sep 23 '22 02:09

Jon Skeet