Java > Logic-1 > withoutDoubles (CodingBat Solution)

Problem:

Return the sum of two 6-sided dice rolls, each in the range 1..6. However, if noDoubles is true, if the two dice show the same value, increment one die to the next value, wrapping around to 1 if its value was 6.

withoutDoubles(2, 3, true) → 5
withoutDoubles(3, 3, true) → 7
withoutDoubles(3, 3, false) → 6


Solution:

public int withoutDoubles(int die1, int die2, boolean noDoubles) {
  if(noDoubles) {
    if (die1 == die2) {
      if (die1 != 6)
        return die1 + 1 + die2;
      else
        return 1 + die2;
    } 
  }
  
  return die1 + die2;
    
}


7 comments :

  1. if (noDoubles&&die1==die2) return (die1!= 6)?die1+1+die2:1+die2;
    return die1 + die2;

    ReplyDelete
  2. if (noDoubles) {
    if (die1 == 6)
    die1 = 1;
    else if (die1 == die2)
    die1 += 1;
    }
    return die1 + die2;

    ReplyDelete
  3. private final int withoutDoubles(int die1, int die2, boolean noDoubles) {
    if (noDoubles && die1 == die2){
    if(die1 == 6){
    return 7;
    }
    return die1+ die2 + 1;
    }
    return die1 + die2;
    }

    ReplyDelete
  4. public int withoutDoubles(int die1, int die2, boolean noDoubles) {
    int sum = die1 + die2;
    if (sum <= 6 && noDoubles == false)
    return sum;
    else if (die1 == 6 && die2 == 6 && noDoubles == true)
    return die1 + 1;
    else if (die1 == die2 && noDoubles == true)
    return sum + 1;
    else
    return sum;
    }

    ReplyDelete
    Replies
    1. public int withoutDoubles(int die1, int die2, boolean noDoubles) {
      int sum = die1 + die2;

      if (die1 == 6 && die2 == 6 && noDoubles == true)
      return die1 + 1;
      else if (die1 == die2 && noDoubles == true)
      return sum + 1;
      else
      return sum;
      }

      Delete
  5. int result=0;
    if(noDoubles&&die1==die2){
    if(die1!=6) result= die1+die2+1;
    else if(die1==6) result= 7;
    }else{
    result= die1+die2;
    }
    return result;

    ReplyDelete
  6. public int withoutDoubles(int die1, int die2, boolean noDoubles) {
    if (noDoubles && die1 == 6 && die2 == 6)
    return die1 + 1;
    else if (noDoubles && die1 == die2)
    return die1+die2+1;
    else return die1+die2;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact