Finding the Minimum Without If
Question: Write a function (in C#) to find the minimum of 2 integers. You cannot use any inbuilt functions that provide this functionality and you cannot use any flow-of-control statements like "if" and "while".
Answer: It would be darn easy if it wasn't for those restrictions in the question! So we need to think outside of the box which is the point of this particular problem. You've probably already guessed that it involves a mathematical trick. Here is a function that uses absolute values... try and see if you can figure out why it works.
static int Min(int a, int b)
{
return (int)(0.5 * (Math.Abs(a + b) - Math.Abs(a - b)));
}
static void Main()
{
int a = 45;
int b = 67;
Console.WriteLine( Min(a,b) );
}
22 Dec 2008 Damien Wintour







