Created
April 28, 2012 23:13
-
-
Save JohnFord/2522557 to your computer and use it in GitHub Desktop.
Challenge from a friend: "Design a function that selects the top k from n items using a reduce." This is my naive 5-min solution.
This file contains hidden or 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
def doit(k, array) | |
array.reduce([]) do |memo,o| | |
if memo.length < k | |
memo << o | |
elsif (min = memo.min) < o | |
memo[memo.index(min)] = o | |
end | |
memo | |
end | |
end | |
array = [1,3,5,7,9,2,4,6,8,10] | |
doit(3, array) #=> [10, 9, 8] | |
doit(4, array) #=> [9, 10, 8, 7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment