views:

1382

answers:

9

----------Updated ------------

codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!

Prototype in PHP

$r = $x - (($x - $y) & (($x - $y) / (29)));

Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)

DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;

----------Original Question----------- I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.

I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.

In order to find the the MAX values I can only perform the following functions

Divide, Multiply, Subtract, Add, NOT, AND ,OR

Let's say I have two numbers

A = 60;
B = 50;

Now if A is always greater than B it would be simple to find the max value

MAX = (A - B) + B;
ex. 
10 = (60 - 50)
10 + 50 = 60 = MAX

Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.

Is there any way possible using the limited operation above to find a value VERY close to the max?

A: 

It depends which language you're using, but the Ternary Operator might be useful.

But then, if you can't perform conditional checks in your 'scripting application', you probably don't have the ternary operator.

pavium
I'm sure if they can't use if, they can't use ?: either
Brian Postow
No conditional statements available in the language.
Cody N
@Brian, that what I said, and got downvoted for it. Maybe conditional statements aren't allowed in answers, too.
pavium
+1  A: 

Hmmm. I assume NOT, AND, and OR are bitwise? If so, there's going to be a bitwise expression to solve this. Note that A | B will give a number >= A and >= B. Perhaps there's a pruning method for selecting the number with the most bits.

To extend, we need the following to determine whether A (0) or B (1) is greater.

truth table:

0|0 = 0  
0|1 = 1
1|0 = 0
1|1 = 0

!A and B

therefore, will give the index of the greater bit. Ergo, compare each bit in both numbers, and when they are different, use the above expression (Not A And B) to determine which number was greater. Start from the most significant bit and proceed down both bytes. If you have no looping construct, manually compare each bit.

Implementing "when they are different":

(A != B) AND (my logic here)

Stefan Kendall
Can't do this without shift (and knowing the size of type in bytes).
ChssPly76
Yes you can. Just and with 2**bit_index to get your comparison numbers.
Stefan Kendall
Remember that "shift" is just multiply/divide by 2.
Stefan Kendall
iftrue, is there a way to implement "and when they are different" without a conditional?
bmb
but not if the shift involves the sign-bit which is the case in my proposal (>>31)
codymanix
@bmb: yes. See the edit.
Stefan Kendall
+3  A: 

If you can't trust your environment to generate the appropriate branchless operations when they are available, see this page for how to proceed. Note the restriction on input range; use a larger integer type for the operation if you cannot guarantee your inputs will fit.

moonshadow
+10  A: 

finding the maximum of 2 variables:

max = a-((a-b)&((a-b)>>31))

where >> is bitwise right-shift (also called SHR or ASR depeding on signedness).

Instead of 31 you use the number of bits your numbers have minus one.

codymanix
+1 Note this is only for 32 bits. If the numbers are 8/16/64 bits - the "31" needs to be altered accordingly.
Roee Adler
Too clever 4me.
Stefan Kendall
If you are not allowed to do shifts:int max(int a, int b){ int c = a - b; int d = c int e = d * -1; int f = e + 1; int g = f return (g * a) | ((g*-1) * b);}I used different variables so you can see what happens at each step.
Alex
In C, sign extension is not required, IIRC, so your code may not work. Also, to be more portable, replace 31 with sizeof(type)*8-1.
strager
Unfort I cannot do shifts.
Cody N
This doesn't work if x-y causes overflow or underflow, too.
strager
@codymanix: An undocumented scripting language used through a weather applications called LEADS.
Cody N
A: 

try this, (but be aware for overflows) (Code in C#)

    public static Int32 Maximum(params Int32[] values)
    {
        Int32 retVal = Int32.MinValue;
        foreach (Int32 i in values)
            retVal += (((i - retVal) >> 31) & (i - retVal));
        return retVal;        
    }
Charles Bretana
+2  A: 

Using logical operations only, short circuit evaluation and assuming the C convention of rounding towards zero, it is possible to express this as:

int lt0(int x) {
    return x && (!!((x-1)/x));
}

int mymax(int a, int b) {
    return lt0(a-b)*b+lt0(b-a)*a;
}

The basic idea is to implement a comparison operator that will return 0 or 1. It's possible to do a similar trick if your scripting language follows the convention of rounding toward the floor value like python does.

Andrew Walker
I did try to implement this method and did not achieve desired results. This did help me figure out that my values are not being rounded down but unfort being converted to doubles. AHH!
Cody N
A: 
#region GetMaximumNumber
/// <summary>
/// Provides method to get maximum values.
/// </summary>
/// <param name="values">Integer array for getting maximum values.</param>
/// <returns>Maximum number from an array.</returns>
private int GetMaximumNumber(params int[] values)
{
  // Declare to store the maximum number.
  int maximumNumber = 0;
  try
  {
    // Check that array is not null and array has an elements.
    if (values != null &&
        values.Length > 0)
    {
      // Sort the array in ascending order for getting maximum value.
      Array.Sort(values);

      // Get the last value from an array which is always maximum.
      maximumNumber = values[values.Length - 1];
    }
  }
  catch (Exception ex)
  {
    throw ex;
  }
  return maximumNumber;
}
#endregion
Munavvar Husein
Did you even read the problem description?
truppo
A: 

I guess this one would be the most simplest if we manage to find difference between two numbers(only the magnitude not sign)

max=((a+b)+|a-b|)/2;

where |a-b|=magnitude of difference between a & b

Aasheash
A: 
function Min(x,y:integer):integer;
  Var
   d:integer;
   abs:integer;
 begin
  d:=x-y;
  abs:=d*(1-2*((3*d) div (3*d+1)));
  Result:=(x+y-abs) div 2;
 end;
Volchik