Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Word Count Solution(Shabbir Saifee) #47

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

shabbirsaifee92
Copy link

@@ -0,0 +1,21 @@
#Generates the count of each word in the file sorted by the maximum occured word first
def wordCount
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not a more object oriented solution?

def wordCount
file = File.open("speech.txt")

words = file.read().downcase().split(/\W+/)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

file = File.open("speech.txt")

words = file.read().downcase().split(/\W+/)
words_map = {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Anytime you instantiate an empty collection in order to iteratively build it up is a good clue that you should probably look to use a method like .map or .reduce

if words_map.has_key?(word)
words_map[word] += 1
else
words_map[word] = 1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hash.new lets you set default values.
https://ruby-doc.org/core-1.9.3/Hash.html

#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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whether you go for a more functional or OOP approach; consider SRP in order to improve readability and maintability.

https://sourcemaking.com/refactoring/smells/long-method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants