Skip to content

Instantly share code, notes, and snippets.

@jfarmer
Forked from leadhkr/gist:f1583f0362b255c51890
Created January 23, 2015 21:50
Show Gist options
  • Save jfarmer/36debb536798b11a3598 to your computer and use it in GitHub Desktop.
Save jfarmer/36debb536798b11a3598 to your computer and use it in GitHub Desktop.
# 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