2016-01-20 84 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}