views:

465

answers:

6

I recently encountered with this question: How to reduce this expression: s>73?61:60;.

The hint given was that Instead of using conditional operator we could use a simple comparison which will work fine.

I am not sure but I think it is possible with some GCC extension,although I am unable to figure it out myself.

EDIT:The whole expression is this : s-=s>73?61:60

+3  A: 

This is such an ugly piece of code that I can't beleive I wrote it, but I think it fulfills the requirement:

My answer to the original question which was s>5?6:9:

9 - (((int)(s > 5)) * 3)

Rewritten for the updated question:

61 - (int)(s > 73)

Anders Abel
Lol, very awesome.
hypoxide
Sorry I was editing when you posted.
nthrgeek
A: 

What is the value of (s>5)? Could you do some arithmetic with that?

Without the hint, I would say this was a bad "gotcha" interview question that requires a particular a-ha insight that's not correlated with ability. With the hint, it's... nice, but dim.

John Marshall
+13  A: 

Just like the other answers:

s -= (s > 73) + 60;

This expression works because the spec defines the results of the relational operators. Section 6.5.8 paragraph 6:

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. The result has type int.

Carl Norum
Thats an elegant solution for a bad question ;)
AraK
This also works in C++, where the result of the comparison is `bool`, and where `+` promotes integer operands, and where `bool` promotes to `0` and `1` for `false` and `true` respectively. (assuming `s` is a plain `int` and not some class).
Johannes Schaub - litb
+1 @Johannes for the C++ perspective.
Carl Norum
Yeah, but is it a *reduction* actually? :D We'd have to look at asm, wouldn't we? ;)
Janusz Lenar
+2  A: 

Maybe this?

60 + !!(s > 73)

The double-bang maps non-zero values to 1 and zero to zero.

Nick Meyer
You don't need to do that, the spec guarantees that the relational operators return 1 or 0. Section 6.5.8 paragraph 6.
Carl Norum
@Carl, thanks, I didn't know that.
Nick Meyer
A: 

If we assume that True = 1 and False = 0, then doesn't this work:

s-= (60 + (s > 73))
Jacob G
+6  A: 

How to reduce this expression: s-=s>73?61:60;

How about:

typedef int Price;
Price getPriceAfterRebate(const Price priceBeforeRebate)
{
  const Price normalRebate = 60;
  const Price superRebate = 61;

  const Price superRebateThreshold = 73;

  Price returnValue = priceBeforeRebate;
  if (priceBeforeRebate > superRebateThreshold)
  {
    returnValue -= superRebate;
  }
  else
  {
    returnValue -= normalRebate;
  }
  return returnValue;
}

Tada! An ugly piece of unmaintainable code is reduced to a readable and maintainable block of code.

Bill
trible rofl'ed lol
Johannes Schaub - litb
+1 for entertainmet value.
Ari
@Ari, litb: Glad you enjoyed it.
Bill