Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Polygons challenge

Sharing is caring!

Problem statement
Identify whether four sides (given by four integers) can form a square, a rectangle, or neither.

Input
You will receive an list of strings, each containing four space-separated integers, which represent the length of the sides of a polygon. The input lines will follow the ‘A B C D’ order as in the following representation:

|-----A-----|
|           |
|           |
D           B
|           |
|           |
|-----C-----|

Output
A single line which contains 3 space-separated integers; representing the number of squares, number of rectangles, and number of other polygons with 4 sides. Note that squares shouldn’t be counted as rectangles. Invalid polygons should also be counted as ‘other polygons’.

Constraints
The four integers representing the sides will be such that: -2000 \le x \le 2000 (Where x represents the integer)

Sample Input

36 30 36 30
15 15 15 15
46 96 90 100
86 86 86 86
100 200 100 200
-100 200 -100 200

Sample Output

2 2 2

Solution

public class Polygons {
    enum Shape {
        Square, Rectangle, Other
    }

    private static Shape shape(int a, int b, int c, int d) {
        if (a<=0 || b<=0 || c<=0 || d <= 0) {
            return Shape.Other;
        }

        if (a==b && b==c && c==d) {
            return Shape.Square;
        }

        if (a==c && b==d) {
            return Shape.Rectangle;
        }

        return Shape.Other;
    }

    public static void main(String[] args) throws FileNotFoundException {
        System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in.txt"));
        Scanner in = new Scanner(System.in);

        Map enumMap  = new EnumMap(Shape.class);
        enumMap.put(Shape.Other,0);
        enumMap.put(Shape.Square,0);
        enumMap.put(Shape.Rectangle,0);

        while (in.hasNext()) {
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            int d = in.nextInt();

            Shape shp = shape(a,b,c,d);
            enumMap.put(shp, enumMap.get(shp)+1);
        }

        System.out.println(enumMap.get(Shape.Square)+" "+enumMap.get(Shape.Rectangle)+" "+ enumMap.get(Shape.Other));
    }
}