3

So it's very common to have for loops ect, but when we have a ternary example such as

int answer = (a < b) ? b : a;

How can we put another ternary after the ? like an enhanced ternary

question:

Given two int values, return whichever value is larger. However if the two values have the same remainder when divided by 5, then the return the smaller value. However, in all cases, if the two values are the same, return 0. Note: the % "mod" operator computes the remainder, e.g. 7 % 5 is 2.

maxMod5(2, 3) → 3
maxMod5(6, 2) → 6
maxMod5(3, 2) → 3

my idea:

public int maxMod5(int a, int b) {
      int answer = ((a < b) ? (a % 5 == b % 5) ? a : b) : a;
}

If a < b, check if modulus 5 equal ect

Hello
  • 123
  • 7
  • `a < b ? (a % 5 == b % 5 ? a : b) : a;` Didn't test it, give it a try. – Maroun Dec 26 '15 at 10:04
  • 5
    Just because you can doesn't mean you should. Consider the readability of the resulting code as well. – adrianbanks Dec 26 '15 at 10:23
  • Agree 100% with @adrianbanks. You will not be able to understand that code tomorrow. Not even speaking of someone else understanding that code ever. There is a reason there exists the `if`-statment. – luk2302 Dec 26 '15 at 10:32
  • I agree, you should not nest ternary operators. However, knowing how to read/write them is useful if you take the OCA exam! – Nick Suwyn Jan 11 '16 at 20:37

2 Answers2

2

You have 4 possible outcomes :

  1. a < b and both have same remainder -> return a
  2. a < b and they don't have same remainder -> return b
  3. a > b and both have same remainder -> return b
  4. a > b and they don't have same remainder -> return a

It doesn't matter which one you return when a == b.

int answer = (a < b) ? ((a % 5 == b % 5) ? a : b) : ((a % 5 == b % 5) ? b : a);

Edit:

I missed the requirement to return 0 when the two numbers are the same. This requires a small addition:

int answer = a==b ? 0 : (a < b) ? ((a % 5 == b % 5) ? a : b) : ((a % 5 == b % 5) ? b : a);
Eran
  • 387,369
  • 54
  • 702
  • 768
0
int ans = (a == b) ? 0 : ((a % 5 == b % 5) ? ((a<b)?a:b) : ((a>b)?a:b));
Ankit Deshpande
  • 3,476
  • 1
  • 29
  • 42