Skip to content

Instantly share code, notes, and snippets.

@JohnFord
Created April 28, 2012 23:13
Show Gist options
  • Save JohnFord/2522557 to your computer and use it in GitHub Desktop.
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.
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