Contents

Find the area of a rectangle (with.Java)

   Apr 28, 2024     3 min read

This is an article about the problem of “Finding the area of a rectangle (with.Java)”.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to get to know myself.

Let’s look at the problem first.

problem

There is a rectangle in a two-dimensional coordinate plane whose sides are parallel to the axis.

When an array dots containing the coordinates of the four vertices of a rectangle [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] is given as a parameter, the solution function returns the area of the rectangle. Try completing it.

Restrictions

  • Length of dots = 4
  • Length of element of dots = 2
  • 256 < element of dots[i] < 256
  • Incorrect input will not be given.

Input/Output Example

dotsresult
[[1, 1], [2, 1], [2, 2], [1, 2]]1
[[-1, -1], [1, 1], [1, -1], [-1, 1]]4

My solution to the problem

class Solution {
     public int solution(int[][] dots) {
         int answer = 0;
         int x = dots[0][0];
         int y = dots[0][1];
         int weight = 0;
         int height = 0;

         for(int i = 1; i < dots.length; i++){
             if(x != dots[i][0]){
                 weight = Math.abs(x - dots[i][0]);
             }
             if(y != dots[i][1]){
                 height = Math.abs(y - dots[i][1]);
             }
         }

         answer = weight * height;
         return answer;
     }
}

Solution explanation

  • Store coordinates of first point: Stores the x and y coordinates of the first point in the given array of points in variables x and y.
  • Calculation of horizontal and vertical length: Repeat from the second point to the last point to find the difference between the x and y coordinates to calculate the horizontal length width and vertical length height, respectively.
  • Calculate the area of a rectangle: Multiply the horizontal length and the vertical length to find the area of the rectangle.
  • Return result: Store the area of the obtained rectangle in the answer variable and return it.

Code Advantages

  • Calculate the width and height based on the first point: Find the area of the rectangle by calculating the width and height based on the first point among the given points.
  • Calculation of absolute values of horizontal and vertical lengths: Calculate the distance between two points as absolute values to obtain the horizontal and vertical lengths.

Code Disadvantages

  • Direction of the square according to the order of the points: The direction of the square may vary depending on the order of the points, and the method of calculating the horizontal and vertical lengths may also vary accordingly. Therefore, it may not handle all cases accurately.