-3

Have the function RectangleArea(strArr) take the array of strings stored in strArr, which will only contain 4 elements and be in the form (x y) where x and y are both integers, and return the area of the rectangle formed by the 4 points on a Cartesian grid. The 4 elements will be in arbitrary order. For example: if strArr is ["(0 0)", "(3 0)", "(0 2)", "(3 2)"] then your program should return 6 because the width of the rectangle is 3 and the height is 2 and the area of a rectangle is equal to the width * height.

For example -

Input: ["(1 1)","(1 3)","(3 1)","(3 3)"]
Output: 4
Input: ["(0 0)","(1 0)","(1 1)","(0 1)"]
Output: 1
Sam
  • 105
  • 2
  • 11

3 Answers3

1

Below function will work provided you input the correct set of coordinates of rectangle

function distance(coord1, coord2) {
  console.log(coord1, coord2);
  return Math.sqrt(Math.pow(coord1[0] - coord2[0], 2) + Math.pow(coord1[1] - coord2[1], 2));
}

function RectangleArea (strArr) {
  if (strArr.length < 4) {
    throw new Error("invalid array passed");
  }
  const numArr = strArr.map(coord => coord.match(/\d/g));

  const width = distance(numArr[0], numArr[1]);
  const height = distance(numArr[1], numArr[2]);
  console.log(width, height);

  return width * height;
}
Tulsi Ram
  • 304
  • 2
  • 7
0

Java Solution:

 public int product(String[] strArr){ 
    int firstValue = Integer.parseInt(String.valueOf(strArr[0].charAt(1)));
    int secondValue = Integer.parseInt(String.valueOf(strArr[0].charAt(3)));
    int height = 0;
    int width= 0;

    for(int i=1; i<strArr.length;i++){
        if(Integer.parseInt(String.valueOf(strArr[i].charAt(1)))==firstValue){
            height = secondValue - Integer.parseInt(String.valueOf(strArr[i].charAt(3)));
        }
        if(Integer.parseInt(String.valueOf(strArr[i].charAt(3)))==secondValue){
            width = firstValue - Integer.parseInt(String.valueOf(strArr[i].charAt(1)));
        }
    }

    return Math.abs(height*width);
}
Swarup Saha
  • 895
  • 2
  • 11
  • 23
0
//c++ code
#include <bits/stdc++.h>
using namespace std;
int product(vector<string>arr){
int fistvalue= arr[0][1]-'0';
int secondvalue=arr[0][3]-'0';
int height=0;
int width=0;
for(int i=1;i<arr.size();i++){
    if(arr[i][1]-'0'==fistvalue){
        height=secondvalue-(arr[i][3]-'0');
    }
    if(arr[i][3]-'0'==secondvalue){
        width=fistvalue-(arr[i][1]-'0');
    }
}
return abs((height*width));
}
int main(){
cout<<product({"(0 0)", "(3 0)", "(0 2)", "(3 2)"});
return 0;}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 14 '21 at 15:11