Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get mid value in C++

Consider three values x, y, z.

What would be the formula to get the mid value (not the mean value but the value which is neither the min nor the max)?

const double min = std::min(x, std::min(y, z));
const double mid = /* what formula here ? */
const double max = std::max(x, std::max(y, z));
like image 683
Vincent Avatar asked May 04 '14 10:05

Vincent


People also ask

How do you find the middle value of 3 numbers in C?

if you are able to find maximum and minimum values, you can find the middle value like this: int a = 1, b = 2, c = 3; int minVal = min(a, b); int maxVal = max(maxVal, c); int midVal = a + b + c - maxVal - minVal; midVal should contain the middle value of those 3 numbers.

How do you find the midpoint of an array?

Find the size n of the array. Usually done by sizeof array / sizeof array[0] . Index array[n/2] to find midpoint.


Video Answer


1 Answers

The answer from this link shared in the comments:

const double mid = std::max(std::min(x,y),std::min(std::max(x,y),z));

Edit - As pointed out by Alan, I missed out on a case. I have given now a more intuitive proof.

Direct Proof: Without Loss of Generality with respect to x and y.
Starting with the innermost expression, min(max(x,y),z) ...

  1. If it returns z, we have found the relations: max(x,y) > z. Then the expression evaluates to max(min(x,y),z). Through this we are able to determine the relation between min(x,y) and z.
    If min(x,y) > z, then z is smaller than x and y both (as the relation becomes: max(x,y) > min(x,y) > z). Therefore the min(x,y) is indeed the median and max(min(x,y),z) returns that.
    If min(x,y) < z, then z is indeed the median (as min(x,y) < z < max(x,y)).

  2. If it returns x, then we have x < z and y < z. The expressions evaluates to: max(min(x,y),x). Since max(x,y) evaluated to x, min(x,y) evaluates to y. Getting the relation z > x > y. We return the max of x and y (as the expression becomes max(y,x)) which is x and also the median. (Note that the proof for y is symmetrical)

Proof Ends


Old Proof - Note it is NOT complete (Direct):

Without loss of generality: Assume x > y > z
Min of x and y is y. And min of (max of x and y) and z is z.
The max of y and z is y which is the median.

Assume x = y > z
Min of x and y say is x. And min of (max of x and y is x) and z is z.
Max of the above two is x, which is the median.

Assume x > y = z
Min of x and y is y. And min of (max of x and y is x) and z is z.
Max of the above two is y, which is the median.

Finally, assume x = y = z
Any of the three numbers will be the median., and the formula used will return some number.

like image 119
digvijay91 Avatar answered Sep 20 '22 22:09

digvijay91