SHould be implemented in PHP.
+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
2009-10-25 07:29:26
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
2009-10-25 07:30:38
Wouldn't work for strings.
Ollie Saunders
2009-10-25 07:54:57
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
2009-10-25 08:24:28
If a == b then it'll also return a.
Joren
2009-10-25 09:44:20
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
2009-10-25 14:59:26
+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
2009-10-25 08:32:06
cool. however, would you expect the '==' operator to work with floating point operands?
bgbg
2009-10-25 09:02:32
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
2009-10-25 09:37:49
@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
2009-10-25 10:34:49
+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
2009-10-25 09:33:47