首先请注意,您可以将非负值的总数放在网格中:
x
3|3
2|23
1|123
0|0123
-+----
|0123y
这里我们可以看到一个模式,其中对角线是您的总数。让我们通过一些系统化的线路来跟踪它们。以下是您可以按顺序遍历它们的方式:
x
3|6
2|37
1|148
0|0259
-+----
|0123y
这里的矩阵包含迭代顺序。
这可以解决x和y为非负数的问题。要获得其余部分,您只需对x和y取相反数,确保它们不为零即可。可以像这样实现:
def generate_triplets(n):
yield 0, (0, 0)
for t in range(1, n + 1):
for x in range(0, t + 1):
y = t - x
yield t, (x, y)
if y > 0:
yield t, (x, -y)
if x > 0:
yield t, (-x, y)
if x > 0 and y > 0:
yield t, (-x, -y)
def generate_pairs(n):
yield from (pair for t, pair in generate_triplets(n))
for t, (x, y) in generate_triplets(3):
print(f'{t} = abs({x}) + abs({y})')
这将输出
0 = abs(0) + abs(0)
1 = abs(0) + abs(1)
1 = abs(0) + abs(-1)
1 = abs(1) + abs(0)
1 = abs(-1) + abs(0)
2 = abs(0) + abs(2)
2 = abs(0) + abs(-2)
2 = abs(1) + abs(1)
2 = abs(1) + abs(-1)
2 = abs(-1) + abs(1)
2 = abs(-1) + abs(-1)
2 = abs(2) + abs(0)
2 = abs(-2) + abs(0)
3 = abs(0) + abs(3)
3 = abs(0) + abs(-3)
3 = abs(1) + abs(2)
3 = abs(1) + abs(-2)
3 = abs(-1) + abs(2)
3 = abs(-1) + abs(-2)
3 = abs(2) + abs(1)
3 = abs(2) + abs(-1)
3 = abs(-2) + abs(1)
3 = abs(-2) + abs(-1)
3 = abs(3) + abs(0)
3 = abs(-3) + abs(0)
或成为一对:
(0, 0)
(0, 1)
(0, -1)
(1, 0)
(-1, 0)
(0, 2)
(0, -2)
(1, 1)
(1, -1)
(-1, 1)
(-1, -1)
(2, 0)
(-2, 0)
...