-
-
Save jfarmer/36debb536798b11a3598 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
# Method name: item_counts | |
# Input: An arbitrary array | |
# | |
# Returns: A hash where every item is a key whose value is the number of times | |
# that item appears in the array | |
# | |
# Prints: Nothing | |
# Version 0.1 | |
# ==================================================== | |
def item_counts(array) | |
counts = {} # Initialize counts to an empty Hash | |
array.each do |item| | |
if counts[item] == nil | |
counts[item] = 1 | |
else | |
counts[item] += 1 | |
end | |
end | |
return counts | |
end | |
# Version 0.2 | |
# ===================================================== | |
def str_to_arr(str) | |
lower_case_string = sanitize(str) | |
frequency_pairs(lower_case_string.split("")) | |
end | |
# Version 0.3 | |
# ================================================ | |
def sanitize(str) | |
str.downcase | |
end | |
# Version 0.4 / 1.0 | |
# ================================================ | |
# if ARGV.size == 0 | |
# print "Please enter a file location: " | |
# input = gets.chomp | |
# file_contents = File.read(input) | |
# else | |
# file_contents = File.read(ARGV[0]) | |
# end | |
# Version 1.1 | |
# ================================================ | |
def frequency_pairs(arr) | |
percentage = {} | |
frequency = item_counts(arr) | |
frequency.each do |k, v| | |
percentage[k] = "#{((v.to_f / arr.size).round(3) * 100)}%" | |
end | |
# percentage.each do |k, v| | |
# puts "#{k} [#{v}]" | |
# end | |
return percentage | |
end | |
def print_frequency(percentage) | |
percentage.each do |k, v| | |
puts "#{k} [#{v}]" | |
end | |
end | |
# TESTS | |
# ================================================ | |
# str_to_arr(file_contents) | |
str_to_arr("Hello, World. My name is Sagar and I'm learning to be a developer.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment