views:

231

answers:

5

SHould be implemented in PHP.

+10  A: 

Standard functions: max() and min()

Ollie Saunders
+1  A: 

The simplest way to implement max/min without comparison operators is to use the built-in PHP functions

$max = max($x, $y);

and

$min = min($x, $y);
pavium
A: 

I don't know how to do it in PHP, but this is more or less pseudo code:

function MAX(var a, var b)
{
    return a-b?a:b;
}
function MIN(var a, var b)
{
    return b-a?a:b;
}
Erich
Wouldn't work for strings.
Ollie Saunders
Hows this gonna work? Unless a == b, these methods will always return `a`. Because afaik, most languages convert any nonzero number to true. Make it a - b > 0, but then you are using a comparison operator (even otherwise you are using it, but only internally).
Amarghosh
If a == b then it'll also return a.
Joren
Well, I didn't realize we'd be doing this with strings. Min/max doesn't make much sense with strings.I might have had a brain fart on how if works... The hardware I'm currently working with at work makes positive true, and negative/0 as false, but I think you're right about it being a JNE in C++/c++ like languages.
Erich
+1  A: 
bool equal(int a, int b){ // we have no comparison operators, so we make our own
    return !(a-b);
}

int abs(int a) {
    return sqrt(a*a); // I don't know whether this uses comparison operators
}

int max(int a, int b) {
    while(equal(abs(a-b), a-b)) // no if, but we must have some kind of control flow
        return a;
    return b;
}

int min(int a, int b) {
    while(equal(abs(a-b), a-b))
        return b;
    return a;
}

P.S. comparison functions could be implemented from abs(), too:

bool ispositive(int a) {
    return a + abs(a);
}

bool greaterthan(int a, int b){
    return ispositive(a-b);
}
Jurily
cool. however, would you expect the '==' operator to work with floating point operands?
bgbg
Nope. As my C teacher told me: "Two floating point numbers are never equal."Also, the <= operator is an axiom in math, so if you have no sqrt() function, you're out of luck. Perhaps one way would be to check for the sign bit, but I don't know if that's applicable in PHP.
Jurily
@Jurily - I hope that your C teacher didn't say that because it is incorrect. What he should have said is that you shouldn't compare two floating point numbers simply using '==', '<' and so on.
Stephen C
Of course, he was referring to rounding errors.
Jurily
+2  A: 

From http://www.coranac.com/documents/bittrick/:

min = b + ((a-b) & (a-b)>>31);
max = a - ((a-b) & (a-b)>>31);

Caveat: works only with signed integers. (well, 32-bit integers in the above snippet, but that can be easily changed.) An explanation of how it works can be found at said link.

int3
Jurily
nope; if a < b, (a-b)>>31 will give you a bit mask with all 1's due to sign extension. Right, I forgot to say in the answer that they had to be signed integers.. but php uses only signed integers, so it should be fine.
int3