2013-08-07 35 views
0

搜索我有一個數組,看起來是這樣的:通過一個未排序的非均勻對數組的最接近進入

[[320, 80], [300, 70], [300, 80], [270, 75], [260, 70], [280, 70]] 

這僅僅是一個片段,實際陣列338大。

我想根據一些輸入找到數組中的下一個邏輯元素。因此,舉例來說,我提供兩個數字,即, 315, 80如果你想找到更大的條目,下一個合乎邏輯的就是320, 80

我不想將邏輯關聯到最近,因爲它取決於您想要更大還是更小的元素。所以我想我的意思是「在所需方向上最接近」

作爲附加要求,第二個數字應儘量保持儘可能接近輸入值,或者第一個數字應儘量保持儘可能接近原始號碼。

我遇到問題時,如275, 70,我想找到下一個最小的。這應該260, 70但我實現不斷採摘280, 70

我目前的實現增加了兩個數字之間的差異,尋找差異最小可能的。我不知道如何執行一個方向。

Python的例子(雖然我真的找一個語言無關的解決方案)

elements = [ [320, 80], 
      [300, 70], 
      [300, 80], 
      [270, 75], 
      [260, 70], 
      [280, 70] 
      ] 

target = [275, 70] 
bestMatch = [] 
bestDifference = 0 

for e in elements: 
    currentDifference = abs((target[0] - e[0]) - (target[1] - e[1])) 

    if not bestMatch or currentDifference < bestDifference: 
     bestMatch = e 
     bestDifference = currentDifference 

print bestMatch 

回答

1

根據您的描述和示例輸入我已經解釋說,你應該採取兩個不同的分,而不是它們之間的差異。然後,您將選擇兩個數字中任何一個的變化最小的元素。

走在了正確的方向,你可以只檢查是否元素,你目前處於比目標

這樣做,你會得到下面的更大或更小:

elements = [ [320, 80], 
      [300, 70], 
      [300, 80], 
      [270, 75], 
      [260, 70], 
      [280, 70] 
      ] 

def nextLogicalElement(target, bigger=True): 
    bestScore = 0 
    bestMatch = [] 
    for e in elements: 
     score = min(abs(target[0] - e[0]), abs(target[1] - e[1])) 

     if bigger and target[0] > e[0] or not bigger and target[0] < e[0]: 
      continue 

     if not bestMatch or score < bestScore: 
      bestMatch = e 
      bestScore = score 

    return bestMatch 

輸出:

>>> print nextLogicalElement([315, 80], bigger=True) 
[320, 80] 
>>> print nextLogicalElement([275, 70], bigger=False) 
[260, 70] 
+0

ahhh,perfect。我在這個問題上遇到了一個真正的心理障礙。謝謝 – Lerp

相關問題