-
-
Save zeroeth/768686 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def count_frequency(word_list) | |
counts = Hash.new(0) | |
for word in word_list | |
counts[word] += 1 | |
end | |
counts | |
end |
This file contains hidden or 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
e: e | |
t: t | |
k: k | |
a: a | |
c: c |
This file contains hidden or 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
# THIS IS SPARTA |
This file contains hidden or 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
require_relative 'words_from_string.rb' | |
require_relative 'count_frequency.rb' | |
raw_text = %{ | |
The problem breaks down into two parts. First, given some test as a | |
string, return a list of words. That sounds like an array. Then, build a | |
count for each distinct word. That sounds like a use for a hash---we can | |
index it with the word and use the corresponding entry to keep a count. | |
} | |
word_list = words_from_string(raw_text) | |
counts = count_frequency(word_list) | |
sorted = counts.sort_by {|word, count| count} | |
top_five = sorted.last(5) | |
for i in 0...5 | |
word = top_five[i][0] | |
count = top_five[i][0] | |
puts "#{word}: #{count}" | |
end |
This file contains hidden or 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
def words_from_string(string) | |
string.downcase.scan(/[\w']+/) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment