如何求数组中最大负数和最小正数

时间:2021-07-13 20:12:10

Are there some methods that can find max negative number and min positive number in array? Array contains no zeros

是否有一些方法可以在数组中找到最大负数和最小正数?数组中不包含零

[-1,5,-4,6,1,8,-3].max_negative # => -1
[-1,5,-4,6,1,8,-3].min_positive # => 1

4 个解决方案

#1


5  

I don't think there's a built in solution. But you can achieve that very simply.

我不认为有现成的解决方案。但你可以很简单地做到这一点。

[-1,5,-4,6,1,8,-3].select{|n| n < 0}.max # => -1
[-1,5,-4,6,1,8,-3].select{|n| n >= 0}.min # => 1

You can even wrap them in a method if you want, maybe in array class.

如果你想的话,你甚至可以把它们封装在一个方法中,比如在数组类中。

#2


6  

[-1,5,-4,6,1,8,-3].select(&:negative?).max
[-1,5,-4,6,1,8,-3].select(&:positive?).min

#3


4  

neg_max, pos_min =  [-1,5,-4,6,1,8,-3].minmax_by{|el| 1.0/el}

#4


0  

Here is one more way to do this - partition the array into positive and negative sub-arrays and then find max/min from each of those two arrays.

这里还有一种方法——将数组划分为正负子数组,然后从这两个数组中找到最大值/最小值。

positives, negatives = arr.partition(&:positive?)
p positives.min
#=> 1
p negatives.max
#=> -1

Alternatively, you could do as below, where array is sorted and a pair is found where first element of pair is negative and second element is positive, thus giving us the values of max negative and min positive values.

或者,你也可以这样做,数组被排序,并且找到一对,其中第一个元素为负,第二个元素为正,这样我们就得到了最大值为负,最小值为正。

max_neg, min_pos = arr.sort.each_slice(2)
                           .select {|i, j| i.negative? and j.positive?}.flatten

#1


5  

I don't think there's a built in solution. But you can achieve that very simply.

我不认为有现成的解决方案。但你可以很简单地做到这一点。

[-1,5,-4,6,1,8,-3].select{|n| n < 0}.max # => -1
[-1,5,-4,6,1,8,-3].select{|n| n >= 0}.min # => 1

You can even wrap them in a method if you want, maybe in array class.

如果你想的话,你甚至可以把它们封装在一个方法中,比如在数组类中。

#2


6  

[-1,5,-4,6,1,8,-3].select(&:negative?).max
[-1,5,-4,6,1,8,-3].select(&:positive?).min

#3


4  

neg_max, pos_min =  [-1,5,-4,6,1,8,-3].minmax_by{|el| 1.0/el}

#4


0  

Here is one more way to do this - partition the array into positive and negative sub-arrays and then find max/min from each of those two arrays.

这里还有一种方法——将数组划分为正负子数组,然后从这两个数组中找到最大值/最小值。

positives, negatives = arr.partition(&:positive?)
p positives.min
#=> 1
p negatives.max
#=> -1

Alternatively, you could do as below, where array is sorted and a pair is found where first element of pair is negative and second element is positive, thus giving us the values of max negative and min positive values.

或者,你也可以这样做,数组被排序,并且找到一对,其中第一个元素为负,第二个元素为正,这样我们就得到了最大值为负,最小值为正。

max_neg, min_pos = arr.sort.each_slice(2)
                           .select {|i, j| i.negative? and j.positive?}.flatten