Created
November 30, 2012 11:51
-
-
Save rklemme/4175335 to your computer and use it in GitHub Desktop.
Obtain the smalles n items from an Enumerable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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