-6

With Java, how would one find the greatest two numbers of a set of 3 numbers without using if conditionals.

For example given the 3 numbers {2,3,5}

int a = 2;
int b = 3;
int c = 5;

int total;

total would be replaced with the value of c+b = 8

chackerian
  • 1,301
  • 2
  • 15
  • 29

3 Answers3

2
List<Integer> data = Arrays.asList(23,6,13);
Collections.sort(data);
Collections.reverse(data)
data = data.sublist(0,2);
System.out.println(data);
f1sh
  • 11,489
  • 3
  • 25
  • 51
  • 2
    I can make that more "efficient" straight away: don't reverse, and use `data.sublist(1, 3)`. Or, of course, sort it with the reverse natural order comparator. – Andy Turner Apr 28 '16 at 14:40
  • @AndyTurner true. But this clarifies very well what happens. – f1sh Apr 28 '16 at 14:46
  • All these methods are using 'if' inside. I suppose that question about something utilizing no conditionals at all (like if/while/etc). There seems to be some investigation of possible solutions for simpler case here http://stackoverflow.com/questions/476800/comparing-two-integers-without-any-comparison – Artur Biesiadowski Apr 28 '16 at 14:49
  • @ArturBiesiadowski and how would you make decisions without using ``if``? – f1sh Apr 28 '16 at 14:52
  • @f1sh I assume that this is what makes it complicated. I don't have answer yet, but for example for simplified case of two different, positive integers, you could find bigger one (assuming condition-free signum method) greater = a x signum(a/b) + b x signum(b/a); I suppose that with enough trickery similar thing can be done for 3 integers. Plus, we need to get condition-free signum, which possibly can be done by some hack with Math.pow involving zeroes or infinities? – Artur Biesiadowski Apr 28 '16 at 15:06
  • Now, with edit to make it sum of two biggest numbers instead of reporting two biggest, it is reasonably simple (again assuming positive integers). Unfortunately cannot paste code in comment, but you do it like int aTest = a/b + a/c; int aTestSign = (int)(((double)aTest)/aTest); and then return sum of aTestSign times a + same for b and c. – Artur Biesiadowski Apr 28 '16 at 15:22
1

One line:

int biggest = (a > b ? a : b) > c ? (a > b ? a : b) : c;

Two lines:

int firstStep = (a > b ? a : b);  
int biggest = firstStep > c ? firstStep : c;
Richard Loth
  • 79
  • 1
  • 7
0

Java 8:

int max  = Arrays.stream(numbers).max().getAsInt();
int sec_max = Arrays.stream(numbers).filter(i -> i != max).max().getAsInt();
Sebastian G.
  • 616
  • 1
  • 7
  • 25