2016-01-20 125 views
-5

若干最接近的值我有一個數組:獲得從陣列

["7", "8", "11", "13", "14"] 

我想最接近劣數11如果任何(即8),或者如果這樣的號碼不存在,則最接近的優越編號爲11(即13)。

+1

實施您描述的方法時發生了什麼?你有沒有得到任何錯誤或錯誤的結果?請描述你的方法和你得到的任何錯誤。有關如何針對Stack Overflow提出問題的詳細信息,請參閱[我可以在這裏詢問哪些主題?](http://stackoverflow.com/help/on-topic)。 –

+0

我不明白你想要什麼。什麼是「最接近的號碼」?按指數,按價值?更具體一點,你總是可以使用[文檔](http://ruby-doc.org/core-2.2.0/Array.html) – nobilik

+0

一些更多的細節將有所幫助。數組是否已排序?你可以重複嗎?你的整型數組是否被實際定義爲一個字符串數組?如果數組是空的呢?整數傳入的限制是什麼?輸入和輸出涵蓋這些案例的例子將幫助我們爲您提供幫助。 –

回答

9
h = ["7", "8", "11", "13", "14"].map(&:to_i).sort.group_by{|e| e <=> 11} 
h[-1].last || h[1].first # => 8 
+2

不錯,sawa! –

+0

對於像我這樣看着「我想要一個數組中最接近3的數字,如果可能的話完全匹配」的人,這裏是你的解決方案: 'tmp = [1,2,3,5,6]。 sort.group_by {| e | e <=> number_to_find}; closest_or_exact_number = tmp.try(:[],0).first || tmp.try(:[],-1).last || tmp [1] .first' – Erowlin

3
def closest(arr, target) 
    return nil if arr.empty? 
    a = (arr + [target]).sort_by(&:to_i) 
    idx = a.rindex(target) 
    idx > 0 ? a[idx-1] : a[idx+1] 
end 

arr = ["11", "7", "13", "8", "11", "14"] 

closest(arr, "12") #=> 11 
closest(arr, "12.5") #=> 11 
closest(arr, "11") #=> 11 
closest(arr, "4") #=> 7 
closest(arr, "7") #=> 7 

編輯:下面是一個使用方法Object#to_enumEnumerator#nextEnumerator#peek另一種方式:

def closest(arr, target) 
    return nil if arr.empty? 
    e = arr.map(&:to_i).sort.to_enum 
    x = nil # initialize to anything 
    loop do 
    x = e.next 
    break if x > target || e.peek > target 
    end 
    x.to_s 
end 

對於arr以上:

closest(arr, 12) #=> 11 
closest(arr, 12.5) #=> 11 
closest(arr, 11) #=> 11 
closest(arr, 4) #=> 7 
closest(arr, 7) #=> 7 

當枚舉數在上屆值,peek將生成一個StopIteration異常。 Kernel#loop通過跳出循環來處理該異常。

2

另一種方式來解決這個問題:

a = arr.map(&:to_i).sort  #=> [7, 8, 11, 13, 14] 
a.reverse.find { |e| e < 11 } #=> 8 
a.find { |e| e > 11 }   #=> 13 

由於find回報nil如果沒有對象相匹配,最後兩行可以合併通過:

a.reverse.find { |e| e < 11 } || a.find { |e| e > 11 } 
+1

...或'a.reverse_each.find ..'以避免創建臨時數組'a.reverse'。 –

1

試試下面最短的方法獲得最接近值

n = 40 
a = [20, 30, 45, 50, 56, 60, 64, 80] 
a.sort.min_by{|x| (n-x).abs}