Number of dice (with.Java)
This article examines the “Number of Dice” problem.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
I have a cuboid-shaped box and I want to fill this box with as many cube-shaped dice as possible.
When the array box, which stores the width, length, and height of the box, and the integer n, the length of the edge of the dice, are given as parameters, complete the solution function to return the maximum number of dice that can fit into the box.
Restrictions
- The length of the box is 3.
- box[0] = horizontal length of the box
- box[1] = vertical length of the box
- box[2] = height length of box
- 1 ≤ element of box ≤ 100
- 1 ≤ n ≤ 50
- elements of n ≤ box
- Place the dice parallel to the box.
Input/Output Example
box | n | result |
---|---|---|
[1, 1, 1] | 1 | 1 |
[10, 8, 6] | 3 | 12 |
My solution to the problem
class Solution {
public int solution(int[] box, int n) {
int answer = 0;
int x = box[0] / n;
int y = box[1] / n;
int z = box[2] / n;
answer = x * y * z;
return answer;
}
}
Solution explanation
This problem involves calculating the volume of a box, given its size and the number to be divided.
To solve the problem, the size of the given box must be divided by each dimension (x, y, z).
You can then calculate the final volume by multiplying the divisions for each dimension.
Divide each dimension (x, y, z) of the box array by n to obtain the division value for each dimension.
Multiply the divided value to calculate the final volume.