1

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]
sawa
  • 165,429
  • 45
  • 277
  • 381
Sylar
  • 11,422
  • 25
  • 93
  • 166

4 Answers4

6

What about this?

a = [1, 1, 2, 3, 3, 4]
min = a.min
a.select { |i| i == min }
 => [1, 1]
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • I think most would go with this; it's a shame it's not an answer in the question for which this question is a duplicate. – Sagar Pandya Apr 26 '17 at 12:17
4

Another way:

a = [1,1,2,3,3,4]

a.group_by(&:itself).min.last
steenslag
  • 79,051
  • 16
  • 138
  • 171
1

Here's one way to solve the problem:

  1. Find the smallest number
  2. Count how many times it appears
  3. Generate an array with the solution instead of selecting elements in the input

Snippet:

input = [1,1,2,3,3,4]
highest = input.min
[highest] * input.count(highest)
yoones
  • 2,394
  • 1
  • 16
  • 20
  • Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* it addresses the question. Without that, your answer has much less educational value - remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Apr 26 '17 at 11:31
  • Using this thinking we can do `Array.new(arr.count(arr.min), arr.min)` – Sagar Pandya Apr 26 '17 at 12:07
  • You could, but then you would traverse the array 3 times when 2 suffice. – yoones Apr 26 '17 at 12:40
0

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]
Ilya
  • 13,337
  • 5
  • 37
  • 53