Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient solution to blackjack? [closed]

Tags:

java

I'm working on the following problem from codingbat:

Given 2 int values greater than 0, return whichever value is nearest to 21 without going over. Return 0 if they both go over.

blackjack(19, 21) → 21

blackjack(21, 19) → 21

blackjack(19, 22) → 19

My solutions is:

public int blackjack(int a, int b) {
  if (a>21){
    if (b>21){ 
     return 0;
   }
   return b;
  }

  else if(b>21) return a;

  return Math.max(a,b);
}

Is there something in my logic that can be improved to make it more efficient? Am I doing something unnecessary?

like image 243
Jamil Avatar asked Aug 12 '11 04:08

Jamil


3 Answers

This could be more efficient. At the very least it's another way of looking at the problem:

public int blackjack(int a, int b) {
  if (a>21) a = 0;
  if (b>21) b = 0;

  if (a>b) {
    return a;
  else {
    return b;
  }
}
like image 83
Charles L. Avatar answered Sep 18 '22 04:09

Charles L.


I wouldn't say this is more efficient, but I re-ordered some of the if statements and arrived at the code below. I think this is, at the very least, somewhat easier to follow:

public int blackjack(int a, int b) {
  if (a <= 21 && b <= 21) return Math.max(a, b);
  if (a <= 21) return a;
  if (b <= 21) return b;
  return 0;
}
like image 30
antonyt Avatar answered Sep 18 '22 04:09

antonyt


Using ternary operator:

public int blackjack(int a, int b) {
    a = a > 21 ? 0 : a;
    b = b > 21 ? 0 : b;
    return (a > b) ? a : b;
}
like image 33
dansalmo Avatar answered Sep 21 '22 04:09

dansalmo