Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created October 18, 2016 21:18
Show Gist options
  • Save VegaFromLyra/762ac80082ab5900dfe4a3f4394a0f59 to your computer and use it in GitHub Desktop.
Save VegaFromLyra/762ac80082ab5900dfe4a3f4394a0f59 to your computer and use it in GitHub Desktop.
Top N words
puts "Enter sentence"
sentence = gets.chomp
puts "You entered '#{sentence}'"
puts "How many top words would you like to see?"
n = gets.chomp.to_i
puts "Alright, let me get that for you.."
words = sentence.split
frequency_map = {}
words.each do |word|
if frequency_map.key?(word)
frequency_map[word] = frequency_map[word] + 1
else
frequency_map[word] = 1
end
end
frequency_map = frequency_map.sort_by {|k, v| v}.reverse
top_n = frequency_map.take(n).map { |k, v| k }
puts "And the winners are:"
top_n.each { |t| puts t }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment