想象一个网站,它每天使用条形图仅以图形形式发布每日通勤人数。我想在将图形保存为图像后通过读取条形图来确定数字(图像的东西在这里并不重要)。我想阅读条形图的方法是转到像素数(#of commuters 轴)并提出问题,“像素是“开”还是“关”?(开意味着存在柱,关意味着这个猜测太高了) 注意:有一个下限为 0,从技术上讲,上限是无限的。但是,实际上,10000 可能是现实的上限。另请注意,与昨天相比没有变化是常见的发现。
给定一个从昨天开始的数字来猜测,找到数字的最有效方法是什么?高效意味着询问像素是打开还是关闭的查询数量最少。
(在我的非 CS 眼中,这似乎是某种寻边二进制搜索,但没有预定义的数组。我可以说我已经学到了很多关于搜索的知识。)
我的算法遵循一个函数。任何建议都是最受欢迎的。
def EdgeFind(BlackOrWhite,oldtrial,high,low):
# BlackOrWhite is a 0 or 1 depending on if the bar is present or not. A 1 indicates that you are below or equal to the true number. A 0 indicates that you are above the true number
# the initial values for oldtrial, high, and low all equal yesterday's value
factorIncrease = 4#5
finished = 0
if BlackOrWhite == 1 and oldtrial==high:
newtrial = oldtrial+factorIncrease*(high-low)+1
high = newtrial
low = oldtrial
elif BlackOrWhite == 1 and high-oldtrial==1:
finished = 1
newtrial = oldtrial
elif BlackOrWhite == 1:
newtrial = oldtrial+(high-oldtrial)/2
low = oldtrial
if BlackOrWhite == 0 and oldtrial==low:
newtrial = (oldtrial)/2
high = oldtrial
low = newtrial
elif BlackOrWhite == 0 and oldtrial-low==1:
finished = 1
newtrial = oldtrial-1
elif BlackOrWhite == 0:
newtrial = oldtrial-(oldtrial-low+1)/2
high = oldtrial
if (oldtrial==1) and low!=1:
finished = 1
return finished,newtrial,high,low