3

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
3
  • Interesting question, but I think you should write "and" rather than "or". Mar 15, 2016 at 18:12
  • You said in a comment that the array contains no zeroes. That is important and therefore should have been said in the question. I suggest you edit to add that, but make it clear that it's an edit (e.g., "Edit: I forgot to mention that the array contains no zeroes."). Mar 15, 2016 at 18:22
  • Please do NOT put "Edit" or "Update" tags in the text. We can tell what changed when if we need to know. Mar 15, 2016 at 19:52

4 Answers 4

6

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.

6
[-1,5,-4,6,1,8,-3].select(&:negative?).max
[-1,5,-4,6,1,8,-3].select(&:positive?).min
1
  • Note these methods were added to Numeric in Ruby 2.3 Jun 22, 2017 at 0:46
4
neg_max, pos_min =  [-1,5,-4,6,1,8,-3].minmax_by{|el| 1.0/el}
3
  • @CarySwoveland Adding a zero to the array results in [-1,0] (because 1.0/0 is Infinity). This may or may not be what OP wants.
    – steenslag
    Mar 15, 2016 at 18:03
  • @CarySwoveland array is zero-free..so this works too Mar 15, 2016 at 18:16
  • This only works if the array contains at least a negative and a positive number.
    – Stefan
    Mar 16, 2016 at 7:42
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
2
  • 2
    The OP is looking for the "positive min" (1) and the "negative max" (-1). Also note that 0 is neither positive? nor negative?
    – Stefan
    Mar 15, 2016 at 17:15
  • @Stefan Thanks for the comment. Have updated the answer
    – Wand Maker
    Mar 16, 2016 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.