Wednesday, December 21, 2011

Find max and min with abs

A colleague of mine showed me two neat tricks he found on Stack Overflow.

To find max and min of a, and b, you can do:

max = ((a + b) + abs(a - b)) / 2
min = ((a + b) - abs(a - b)) / 2

However, I wouldn't recommend any code like this, unless you have no other choice. To quote Abelson and Sussman:
Programs must be written for people to read.
Those two lines aren't really meant for people to read. A little bit cryptic, don't you think? Just like a swap with exclusive ors.

No comments:

Post a Comment