Monday 12 August 2013

Area Calculator


Given an orthogonal polygon, calculate the area, and print it on screen. You will be given input as pairs of direction and length. Input will be provided in the form, direction indicator NEWS, followed by the distance indicator 1-99.

Sample
Input => N5 E5 S5 W5.
Output => 25
Reason => This is a square of side 5, area is 25.

Input => N10 E2 S8 E8 S2 W10
Output => 36
Reason => Depicts L shape. This can be computed as Vertical Rectangle = 2x8, Horizontal Rectangle = 2x8 and common square = 2x2.


Solution:

class CalculateArea{
//convert the given directions into the cordintates
static int[][] convertDirectionToCordinate(String []directions){
if(directions == null || directions.length == 0)
return null;

int len = directions.length;
int [][]cordinates = new int[len][2];
cordinates[0][0] = 0;
cordinates[0][1] = 0;

for(int i = 0; i < directions.length; i++){
char ch = directions[i].charAt(0);
if(ch == 'N'){
if(i == 0){
cordinates[i][1] =  getValue(directions[i]);
}else{
cordinates[i][1] = cordinates[i-1][1] + getValue(directions[i]);
}
}else if(ch == 'E'){
cordinates[i][0] = cordinates[i-1][0] + getValue(directions[i]);
cordinates[i][1] = cordinates[i-1][1];
}else if(ch == 'S'){
cordinates[i][1] = cordinates[i-1][1] - getValue(directions[i]);
cordinates[i][0] = cordinates[i-1][0] ;
}else if(ch == 'W'){
cordinates[i][0] = cordinates[i-1][0] - getValue(directions[i]);
cordinates[i][1] = cordinates[i-1][1];
}
}
return cordinates;
}

public static int getValue(String str){
if(str.length() == 3)
return (str.charAt(1) - '0')*10 + str.charAt(2) - '0';
return str.charAt(1) - '0' ;
}

//calculate the area of any polygon when cordinates of polygon are given
//time : O(N) N : Number of cordinates of polygon
public static int area(int [][]cordinates){
if(cordinates == null || cordinates.length == 0)
return -1;

int area = 0;
int len = cordinates.length;
int j = len - 1;

for(int i = 0; i < len; i++){
area += (cordinates[j][0] + cordinates[i][0]) * (cordinates[j][1] - cordinates[i][1]);
j = i;
}
return area/2;
}

public static void main(String ...args){
//String directions[] = {"N5", "E5", "S5", "W5"};
String directions[] = {"N10", "E2", "S8", "E8", "S2", "W10"};
int [][] cordi = convertDirectionToCordinate(directions);

int area = area(cordi);
System.out.println("area : "+area);
}
}

No comments:

Post a Comment