Created
October 18, 2016 21:18
-
-
Save VegaFromLyra/762ac80082ab5900dfe4a3f4394a0f59 to your computer and use it in GitHub Desktop.
Top N words
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
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