Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

javascript - Function to find area of a rectangle with given cartesian coordinates

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...