Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Obtain the smalles n items from an Enumerable
module Enumerable
def n_min(n)
raise "Illegal argument: #{n.inspect}" unless n > 0
mins = []
each do |item|
mins.push item
mins.sort!
mins.pop if mins.size > n
end
mins
end
end
module Enumerable
def n_min(n)
raise "Illegal argument: #{n.inspect}" unless n > 0
mins = []
each do |item|
mins.size.times do |i|
if item < mins[i]
mins.insert i, item
break false
end
end and mins.push item
mins.pop if mins.size > n
end
mins
end
end
module Enumerable
def n_min(n)
raise "Illegal argument: #{n.inspect}" unless n > 0
mins = []
each do |item|
mins.size.times do |i|
if item < mins[i]
mins.insert i, item
mins.pop if mins.size > n
break false
end
end and mins.size < n and mins.push item
end
mins
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.