我正在研究一种在大图像上随机绘制对象的算法。这是我目前拥有的工作流程。
问题如下,随着绘制更多的对象,数组的大小-strictList增加。每次迭代都需要更长的时间来选择有效的随机点。我在这里看到的最大缺陷是,我反复从图像空间中选择一个随机坐标,从而浪费了处理能力。我尝试的一种替代方法是使用数组-[x for x in AllPossiblePoints if x not in restrictList]
并选择一个随机索引。因为数组AllPossiblePoints非常大,所以花费的时间甚至更长。我想我需要一种方法来确保strictList中的(x,y)坐标不会首先随机生成。
def genLoc(x,y, restrictList):
Valx = randint(0, x)
Valy = randint(0, y)
point = (Valx, Valy)
if point in restrictList:
return genLoc(dimx, dimy, restrictList)
elif point not in restrictList:
return point
答案 0 :(得分:0)
已修订
此解决方案将要求您提前生成所有可能的坐标。它使用集合和集合逻辑来消除使用时的可能性。 random.sample用于从可能的位置中选择一个点。我想做些什么来说明-(一切都是 linear )。
import random
# fake function that identifies
# unusable points after placing an object
def calc_objectspace(point,obj=None):
objdims = range(-5,5)
# linear all the same size
objspace = set(point+n for n in range(-5,5))
objspace.add(point) # as needed
return objspace
# make all the points as a set
allthestuff = set(range(10000))
# iterate over the objects getting placed
for obj in range(10):
# random.choice won't work with a set
point = random.sample(allthestuff,1)[0]
# determine occupied points
obj_space = calc_objectspace(point)
# reduce the possible points
allthestuff.difference_update(obj_space)
print(len(allthestuff))
s.difference_update(t)
的时间复杂度为O(len(t))。
这解决了寻找尚未使用的随机坐标的问题。
无法评估最前创建所有坐标的成本。如果成本太高,则可能必须重新寻找可用的坐标。使用一组来保存所有 restricted 点将减少成员资格测试的时间。