I need to return the smallest numbers (can be more than one) that occur in an array.
given [1,1,2,3,3,4]
expected [1,1]
given [8,8,2,3]
expected [2]
I need to return the smallest numbers (can be more than one) that occur in an array.
given [1,1,2,3,3,4]
expected [1,1]
given [8,8,2,3]
expected [2]
What about this?
a = [1, 1, 2, 3, 3, 4]
min = a.min
a.select { |i| i == min }
=> [1, 1]
Another way:
a = [1,1,2,3,3,4]
a.group_by(&:itself).min.last
Here's one way to solve the problem:
Snippet:
input = [1,1,2,3,3,4]
highest = input.min
[highest] * input.count(highest)
Also, you can use take_while
:
sorted = a.sort
sorted.take_while { |e| e == sorted[0] }
=> [1, 1]
Other possible way:
a = [1, 1, 2, 3, 3, 4]
Array.new(*a.each_with_object(Hash.new(0)) {|e, acc| acc[e] += 1}.min.reverse)
=> [1, 1]