From 02f4f71ee5a440e1401283d7acd8922fd63a31f6 Mon Sep 17 00:00:00 2001 From: shabbir Date: Wed, 21 Feb 2018 14:23:43 -0500 Subject: [PATCH] Word Count Solution --- word_count.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 word_count.rb diff --git a/word_count.rb b/word_count.rb new file mode 100644 index 0000000..91a8f5d --- /dev/null +++ b/word_count.rb @@ -0,0 +1,21 @@ +#Generates the count of each word in the file sorted by the maximum occured word first +def wordCount + file = File.open("speech.txt") + + words = file.read().downcase().split(/\W+/) + words_map = {} + words.map do |word| + if words_map.has_key?(word) + words_map[word] += 1 + else + words_map[word] = 1 + end + end + #words_map.sort {|x,y| -(x[1]<=>y[1])} -- 16.7s + #words_map.sort {|x,y| y[1] <=> x[1]} -- 12.3s + #words_map.sort_by {|k,v| -v} -- 5.9s + #words_map.sort_by {|k,v| v}.reverse -- 3.7 + puts words_map.sort_by {|k,v| v}.reverse.to_h +end + +wordCount