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
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
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.
[-1,5,-4,6,1,8,-3].select(&:negative?).max
[-1,5,-4,6,1,8,-3].select(&:positive?).min
neg_max, pos_min = [-1,5,-4,6,1,8,-3].minmax_by{|el| 1.0/el}
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
0
is neither positive?
nor negative?