Valhalla Legends Archive

Programming => General Programming => Topic started by: TangoFour on December 07, 2004, 03:53 PM

Title: Minimum and Maximum of 3 integers
Post by: TangoFour on December 07, 2004, 03:53 PM
I think one of my teachers once mentioned it, but I can't seem to figure it out:

Is there a way to determine the Minimum and Maximum of 3 integers with just 2 equations?

Let's say we have 3 integers:

a = 14
b = 1337
c = 666

Can I determine the minimum and maximum with just 2 equations?
Title: Re: Minimum and Maximum of 3 integers
Post by: iago on December 07, 2004, 04:18 PM
It depends how you define equations.  You can do it with 2 if's:
int a = 14;
int b = 1337;
int c = 666;
int max = a;
int min = a;
if(max < b || max < c)
  max = b < c ? c : b;
if(min > b || min > c)
  min = b > c ? c : b;

At this point, the max and min will be in the proper variables, unless I made a logical mistake.  And it uses 2 if statements, technically. :)
Title: Re: Minimum and Maximum of 3 integers
Post by: TangoFour on December 07, 2004, 04:35 PM
With equations I meant comparisons between 2 integers
Title: Re: Minimum and Maximum of 3 integers
Post by: Yoni on December 07, 2004, 05:47 PM
iago's code uses 6 comparisons.
It can be done easily with 3 comparisons.

You can't guarantee being able to do it with less than 3 comparisons.
That is, you can do it with 2, but not always. This can be proven mathematically.
(I didn't consider comparisons of sizes that aren't a,b,c, like a+b>c. I think it still can't be done with 2 comparisons but can't prove it right now.)

Riddle: It is possible to find the minimum and maximum of an array of n integers at the same time using only (1.5n + Const) comparisons, instead of the obvious "find minimum, then find maximum" which takes (2n + Const) comparisons. How?

Edit: Wrote "Const" instead of O(1) in case some readers are unfamiliar with the O notation.
Title: Re: Minimum and Maximum of 3 integers
Post by: iago on December 07, 2004, 07:38 PM
He said "2 EQUATIONS", not comparisons! :P
Title: Re: Minimum and Maximum of 3 integers
Post by: TangoFour on December 08, 2004, 03:36 AM
I meant comparisons, I stated that in my reply, sorry for being unclear iago  ;)
Title: Re: Minimum and Maximum of 3 integers
Post by: Adron on December 08, 2004, 05:31 PM
Here it's done in a single equation:

((max = a) || 1) && ((max < b) || (max = b) || 1) && ((max < c) || (max = c) || 1) && ((min = a) || 1) && ((min > b) || (min = b) || 1) && ((min > c) || (min = c) || 1);


:P