How to Find the Area or Perimeter of a 4-sided Polygon using Java

The challenge

You are given the length and width of a 4-sided polygon. The polygon can either be a rectangle or a square.
If it is a square, return its area. If it is a rectangle, return its perimeter.

area_or_perimeter(6, 10) --> 32
area_or_perimeter(4, 4) --> 16

Note: for the purposes of this challenge you will assume that it is a square if its length and width are equal, otherwise, it is a rectangle.

The solution in Java

Given that we know that:

The area of a square is: l x h and the area of a rectangle is 2(l+h), we can create the following code, differentiating on the if conditional statement that l==w, or, length is equal to width, which would mean a square, otherwise a rectangle:

public class Solution {
    public static int areaOrPerimeter (int l, int w) {
        if (l==w) {
          //square
          return l*w;
        } else {
          //rect
          return (l+w)*2;
        }
    }
}

We can simplify this as follows:

public class Solution {
    public static int areaOrPerimeter (int l, int w) {
      return (l==w) ? l*w : (l+w)*2;
    }
}

Test cases to validate our code

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
    private static int X(int a , int b) {
        return a == b ? a * b : 2 * ( a + b );
    }
    @Test
    public void Tests() {
        assertEquals(16, Solution.areaOrPerimeter(4 , 4));
        assertEquals(32, Solution.areaOrPerimeter(6, 10), 32);
        for(int i = 1; i < 101; i++) {
            int a = (int)(Math. random() * (i + 50) + 1);
            int b = (int)(Math. random() * (i + 30) + 21);
            System.out.println("Testing for " + a + ", " + b);
            assertEquals(X(a, b), Solution.areaOrPerimeter(a, b));
        }
    }
}
Tags:
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments