【问题标题】:Progressive loop through pairs of increasing integers通过成对递增整数的渐进循环
【发布时间】:2012-06-23 20:39:27
【问题描述】:

假设一个人想要搜索满足某个等式的整数对 x 和 y a,例如(不由自主地)7 x^2 + x y - 3 y^2 = 5

(我知道有非常有效的方法可以找到这样的二次方程的整数解;但这与当前问题的目的无关。)

显而易见的方法是使用简单的双循环“for x = -max to max; for y = -max to max { blah}” 但是为了让搜索可以停止和恢复,更方便的方法,如图x 和 y 的可能整数作为平面中点的方格,是从原点向外绕“方螺旋”工作,在(例如)右上角开始和停止。

所以基本上,我要求一个简单而合理的“伪代码”用于循环分别在 (m, m) 和 (n, n) 点开始和停止这个过程。

为了额外的荣誉,如果读者倾向于,我建议如果 x 之一可以被假定为非负数,或者如果两者都可以被假定为非负数,我建议也提供循环。这可能更容易一些,尤其是第二个。

我自己可以毫不费力地提出这个问题,但我有兴趣看到其他人的巧妙想法。

对于那些喜欢用白板折磨候选人的可怕面试官来说,这将是一个很好的“建设性”面试挑战;-)

【问题讨论】:

标签: arrays


【解决方案1】:
def enumerateIntegerPairs(fromRadius, toRadius):
    for radius in range(fromRadius, toRadius + 1):
        if radius == 0: yield (0, 0)
        for x in range(-radius, radius): yield (x, radius)
        for y in range(-radius, radius): yield (radius, -y)
        for x in range(-radius, radius): yield (-x, -radius)
        for y in range(-radius, radius): yield (-radius, y)

【讨论】:

    【解决方案2】:

    这是一个简单的实现(也在ideone):

    void turn(int *dr, int *dc) {
        int tmp = *dc;
        *dc = -*dr;
        *dr = tmp;
    }
    int main(void) {
        int N = 3;
        int r = 0, c = 0;
        int sz = 0;
        int dr = 1, dc = 0, cnt = 0;
        while (r != N+1 && c != N+1) {
            printf("%d %d\n", r, c);
            if (cnt == sz) {
                turn(&dr, &dc);
                cnt = 0;
                if (dr == 0 && dc == -1) {
                    r++;
                    c++;
                    sz += 2;
                }
            }
            cnt++;
            r += dr;
            c += dc;
        }
        return 0;
    }
    

    实现中的关键是turn 函数,它在给定一对{delta-Row, delta-Col} 的情况下执行右转。剩下的就是简单的算术。

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 1970-01-01
      • 2017-05-05
      • 2013-09-21
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多