1。请在Codesignal.com 2上解释此矩形旋转解决方案。请解释为什么我的解决方案不起作用

问题描述 投票:0回答:1

我找到了一个我不理解的简单解决方案。这是代码。

def rectangleRotation(a, b):
    pt = 0
    radius = pow(a/2,2)+pow(b/2,2)
    radius = int(math.ceil(pow(radius,.5)))

    for i in range(-radius,radius+1):
        for j in range(-radius,radius+1):
            x = i*math.cos(math.radians(-45)) - j*math.sin(math.radians(-45))
            y = i*math.sin(math.radians(-45)) + j*math.cos(math.radians(-45))
            if -a/2<=x<=a/2 and -b/2<=y<=b/2:
                pt += 1
    return pt

问题陈述是

“在笛卡尔平面上绘制边等于偶数整数a和b的矩形。其中心(其对角线的交点)与点(0,0)重合,但是矩形的边不平行到轴;相反,它们与轴成45度角。给定矩形内(包括其侧面)有多少个整数坐标点?”]

我试图使用sohcahtoa解决问题,并为矩形的较小部分写下了一系列方程式,其中包括最上面和最右边的y截距。我使用trig计算了有效的x范围。我还计算了矩形的上下边界的变化位置。我的代码比解决方案复杂得多,而且我了解人们是否不想回答问题的第二部分,但这对我有很大帮助。

int rectangleRotation(int a, int b) {
    // let y1 be the y intercept for the upper line of the rectangle     
    double y1 = b/sqrt(2);
    // let y2 be the y intercept for the right line of the rectangle
    double y2 = a/sqrt(2);
    // let xyrange be the ceil of the range of x and y
    int xyrange = floor((sqrt(2)/4)*(a + b));
    // let x1 be the point at which the lower/upper line changes
    double x1 = (sqrt(2)/4)*(a - b);
    // let points be the number of points within the rectangle
    int points = 0;
    for (int i = -xyrange; i <= xyrange; i++) {
        // let ru be the floor of upper line value of the rectangle at i
        double ru;
        // check if the upper line changed
        if (i >= ceil(x1)) {
            ru = -i + y2;
        } else {
            ru = i + y1;
        }
        // let rui be the integer bound for the upper line
        int rui;
        if (ru <= 0) {
            rui = ceil(ru);
        } else {
            rui = floor(ru);
        }
        // let rl be the ceil of lower line value of the rectangle at i
        double rl;
        // check if the lower line changed
        if (i <= -floor(x1)) {
            rl = -i - y2;
        } else {
            rl = i - y1;
        }
        // let rui be the integer bound for the upper line
        int rli;
        if (rl <= 0) {
            rli = ceil(rl);
        } else {
            rli = floor(rl);
        }
        for (int j = -xyrange; j <= xyrange; j++) {
            if (j <= rui && j >= rli) {
                points++;
            }
        }
    }
    return points;
}

我得到的答案对于大多数测试用例来说都太高了,并且根据a和b的值,在正确答案之上的5到50之间变化,a和b越高,差异越大。对于a = 6和b = 4,我期望输出为23,但得到27。

algorithm trigonometry
1个回答
0
投票

不只是

function f(a, b){
  let bigger = Math.max(a, b)
  let smaller = Math.min(a, b)
  // Most northeast point (x, x)
  let x = Math.floor(Math.sqrt(bigger * bigger /8))
  let outer_rectangle = (2 * x + 1) *
    (2 * Math.floor(Math.sqrt(smaller * smaller /8)) + 1)
  // Vertical down from (x, x) as hypotenuse
  let y = (Math.floor(Math.sqrt(smaller * smaller / 2)) + 1) >> 1
  
  return outer_rectangle + 4 * x * y
}

console.log(f(6, 4))

使用毕达哥拉斯?

© www.soinside.com 2019 - 2024. All rights reserved.