解答:
想法:
遍历点,当当前遍历的长度大于平均长度时,target就在这条边上。
根据之前的last_len以及现有两点的趋势(x平还是y平)来决定 target的增益以及方向(上下左右)。
细节:
1 为了让点遍历能回到 原点 ,在数组后面添加一个 头
2 对应的生成长度数组 存储长度数据(同样要在尾部加 头),得到target点之间的长度average_len(t0到t1的长度)
3 last_len存储 到当前边时, 其前面 target到新边的长度(图中理解为p0到p2的长度 以及t1到p4的长度等)
4 每一次到新点,使用divmod得到 商 余。商大于1证明在此边上,然后得到其增益gain(average - last(p2到t1的长度))
5 该边上可能存在多个target,对于a的范围进行遍历,累加average_len作为增益
6 商大于零 操作完最后last赋值为余。商等于0,last赋值为current_len
代码:
class Solution:
def find_position(self,arr,k):
res = []
arr_len = self.find_len(arr) # relative array with the length of edges
average_len = sum(arr_len[:-1])/k # average length of ploygon basing on k(delete last one)
last_len = 0 #record the length of last edges when find the target points
arr += [arr[0]] #put the first on the last to do iteration(help we judge the last edge)
for i in range(1,len(arr)):#go through all points of polygon
current_len = arr_len[i-1] +last_len #when we come to new edge, the length equals to last + itself
a,b = divmod(current_len,average_len) # divmod to find quotient and remainder
a= int(a) # avoid of decimal
if a >0:#mean target point is on this edge
x_tend = arr[i][0] - arr[i-1][0]
y_tend = arr[i][1] - arr[i-1][1]
if x_tend ==0:#target point has same x with arr[i]
y_gain = y_tend/abs(y_tend)#the direction of y(up or down)
for j in range(1,a+1):#mean several target points are on this edge
gain = j*average_len - last_len
point = [arr[i-1][0],arr[i-1][1]+gain*y_gain]#gain and its direction
res.append(point)
else:#y
x_gain = x_tend/abs(x_tend)
for k in range(1,a+1):
gain = k*average_len - last_len
point = [arr[i-1][0]+gain*x_gain,arr[i-1][1]]
res.append(point)
last_len = b # in next iteration, last_ is the remainder
elif a ==0:#when a =0, the target point are not on this edge, last_ equals to current_
last_len = current_len
return res
def find_len(self,arr):
arr_len = []
for i in range(1,len(arr)):
x = arr[i][0]
x0 = arr[i-1][0]
if x == x0:
leng = abs(arr[i][1]-arr[i-1][1])
else:
leng = abs(x-x0)
arr_len.append(leng)
arr_len.append(abs(arr[-1][0] - arr[0][0]))
return arr_len+[arr_len[0]] #put the first on the last to do iteration(help we judge the last edge)
su = Solution()
arr = [[1,1],[1,2],[2,2],[2,3],[4,3],[4,1]]
k = 8
res = su.find_position(arr,k)
print(res)
k为4时结果:
[[2, 2.5], [4.0, 3], [3.5, 1], [1.0, 1]]
k为8时结果:
[[1.25, 2], [2, 2.5], [2.75, 3], [4.0, 3], [4, 1.75], [3.5, 1], [2.25, 1], [1.0, 1]]