问题描述
所以就像标题说的那样,我需要帮助尝试将点从 2d 平面映射到数轴,使每个点都与唯一的正整数相关联。换句话说,我需要一个函数 f:ZxZ->Z+ 并且我需要 f 是单射的。此外,我需要在合理的时间内运行。
所以我认为这样做的方法基本上只是计算点数,从 (1,1) 开始并向外螺旋。
下面我写了一些 python 代码来做这件事 (i,j)
def plot_to_int(i,j):
a=max(i,j) #we want to find which "square" we are in
b=(a-1)^2 #we can start the count from the last square
J=abs(j)
I=abs(i)
if i>0 and j>0: #the first quadrant
#we start counting anticlockwise
if I>J:
b+=J
#we start from the edge and count up along j
else:
b+=J+(J-i)
#when we turn the corner,we add to the count,increasing as i decreases
elif i<0 and j>0: #the second quadrant
b+=2a-1 #the total count from the first quadrant
if J>I:
b+=I
else:
b+=I+(I-J)
elif i<0 and j<0: #the third quadrant
b+=(2a-1)2 #the count from the first two quadrants
if I>J:
b+=J
else:
b+=J+(J-I)
else:
b+=(2a-1)3
if J>I:
b+=I
else:
b+=I+(I-J)
return b
我很确定这有效,但正如您所见,它是一个相当庞大的功能。我正在想办法简化这种“螺旋计数”逻辑。或者如果有另一种更简单的计数方法也可以工作。
解决方法
这是一个不成熟的想法:
- 对于每个点,计算
f = x + (y-y_min)/(y_max-y_min)
- 找出任何给定的
d
和f_n
之间的最小增量f_{n+1}
。将所有f
值乘以1/d
,使所有f
值至少相隔 1。 - 取所有
floor()
值中的f
。
这有点像在 x 轴上的投影,但它会尝试分散值以保持唯一性。
更新:
如果您不知道所有数据并且将来需要输入新数据,也许有一种方法可以在步骤中为 y_max
和 y_min
硬编码任意大小的常量1,以及根据您期望的数据值的边界,第 2 步的任意增量 d
。或者根据浮点运算的限制计算这些值的方法。