Contents

Dice Game 1 (with.Java)

   Nov 30, 2023     2 min read

This is a recap of the “Dice Game 1” problem.

We’re going to learn by solving coding test problems, reflecting on the problems we’ve solved, and exploring other ways to solve them.

Let’s start with the problem.

Problem

You have two dice with the numbers 1 through 6 written on them. Let’s call the numbers that come up when the two dice are rolled A and B, respectively.

If both A and B are odd, you get a score of A2 + B2.

If only one of A and B is odd, you get 2 × (A + B) points.

If neither a nor b is odd, you geta - bpoints.

Write a solution function that returns the number of points you get, given two integers a and b as parameters.

Example input and output

abresult
3534
6114
242

My solution to the ### problem

class Solution {
    public int solution(int a, int b) {
        int answer = 0;
        int oddA = a % 2;
        int oddB = b % 2;
        if(oddA != 0 && oddB != 0){
            answer = (int)(Math.pow(a, 2) + Math.pow(b, 2));
        }else if(oddA == 0 && oddB == 0){
            answer = Math.abs(a - b);
        }else{
            answer = 2 * (a + b);
        }
        return answer;
    }
}

Solution explanation

If both a and b are odd, add the squares of the two numbers.

If both a and b are even, return the difference between the two numbers as the absolute value.

Otherwise, add the two numbers and multiply the result by 2.

Here’s the code in a nutshell

int answer = 0;: Initialize an integer variable, answer, to store the result.

int oddA = a % 2; and int oddB = b % 2;: Use the remainder operation to determine if a and b are odd or even, and store it in the oddA and oddB variables. If they are odd, the remainder will be 1, and if they are even, the remainder will be 0.

if(oddA != 0 && oddB != 0) : If both a and b are odd:

Store the sum of the squares of a and b in answer.

else if(oddA == 0 && oddB == 0) : If a and b are both even:

Find the difference between a and b, take the absolute value, and store it in answer.

else : Otherwise (when one is odd and one is even):

Adds a and b, then multiplies the result by 2 and stores it in answer.

return answer;: Returns the calculated result.