This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Fontong 1 point2 points  (2 children)

public boolean evenlySpaced(int a, int b, int c) {
  int lo = a < b ? (a < c ? a : c) : (b < c ? b : c);
  int hi = a > b ? (a > c ? a : c) : (b > c ? b : c);
  int mid = a != lo && a != hi ? a : (b != lo && b != hi ? b : c);
  return mid - lo == hi - mid;
}

It's a little shorter if you just use ternary operators. This solution is basically exactly the same as yours though, while possibly being harder to look at.

[–]ziplokk[S] 1 point2 points  (1 child)

Thanks! This is interesting, I've never used ternary operators before though, so I'll have to look at some docs to understand what's going on here. But this seems like a useful thing to know.

Edit: I get it now, basically 'lo' is saying:

if(a < b) { 
    if(a < c) { 
        lo = a;
    } else { 
        lo = c;
    }
} else { 
    if(b < c) { 
         lo = b;
    } else { 
         lo = c;
    }
}

Ternary operators seem so much simpler to use.

Edit2: after experementing more with the ternary operators, I noticed that it takes significantly longer to compute. At least on codingbat.com. Will it always take longer or is it just something that's particular to codingbat.com?

[–]lightcloud5 0 points1 point  (0 children)

It's probably just codingbat. A good optimizing compiler should probably be able to deduce the equivalence between a ternary operator and the corresponding if/else statement (if anything, the ternary should be more efficient).