Javascript 函数查找具有给定笛卡尔坐标的矩形的面积
让函数RectangleArea(strArr)获取存储在strArr中的字符串数组,该数组将只包含4个元素,其形式为(xy),其中x和y都是整数,并返回由笛卡尔网格上的4个点形成的矩形区域。这4个元素将按任意顺序排列。例如:如果strArr为[“(0 0)”,“(3 0)”,“(0 2)”,“(3 2)”],则程序应返回6,因为矩形的宽度为3,高度为2,矩形的面积等于宽度*高度 比如说-Javascript 函数查找具有给定笛卡尔坐标的矩形的面积,javascript,function,area,Javascript,Function,Area,让函数RectangleArea(strArr)获取存储在strArr中的字符串数组,该数组将只包含4个元素,其形式为(xy),其中x和y都是整数,并返回由笛卡尔网格上的4个点形成的矩形区域。这4个元素将按任意顺序排列。例如:如果strArr为[“(0 0)”,“(3 0)”,“(0 2)”,“(3 2)”],则程序应返回6,因为矩形的宽度为3,高度为2,矩形的面积等于宽度*高度 比如说- Input: ["(1 1)","(1 3)","(3
Input: ["(1 1)","(1 3)","(3 1)","(3 3)"]
Output: 4
如果您输入正确的矩形坐标集,下面的函数将起作用
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;
}
函数距离(坐标1,坐标2){
console.log(coord1,coord2);
返回Math.sqrt(Math.pow(coord1[0]-coord2[0,2)+Math.pow(coord1[1]-coord2[1,2));
}
功能矩形区域(strArr){
如果(直线长度<4){
抛出新错误(“传递的数组无效”);
}
const numArr=strArr.map(coord=>coord.match(/\d/g));
常数宽度=距离(努马尔[0],努马尔[1]);
常数高度=距离(努马尔[1],努马尔[2]);
控制台。原木(宽度、高度);
返回宽度*高度;
}
Java解决方案:
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);
}
public int乘积(String[]strArr){
int firstValue=Integer.parseInt(String.valueOf(strArr[0].charAt(1));
int secondValue=Integer.parseInt(String.valueOf(strArr[0].charAt(3));
整数高度=0;
整数宽度=0;
对于(int i=1;ii在您的两个示例中,坐标的顺序是不同的。@NikhilPatil它实际上应该返回基于该输入顺序的答案。对于示例测试用例,它首先给出了错误的答案5.656。经过一些更改后,我得到了它。感谢您的帮助。
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);
}