Created
January 11, 2013 12:37
-
-
Save hackjoy/4510355 to your computer and use it in GitHub Desktop.
A method to count the frequency that each value within a string of comma separated values appears in another string of comma separated values.
Usage: count_frequency_of_string_values(["1,2,"], ["1,2,2,2"]) => ["1-1", "2-3"]
This file contains 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 'benchmark' | |
require 'test/unit' | |
def count_frequency_of_string_values(key, observation) | |
# convert arguments into arrays for comparison | |
key_array = key.split(",").map { |s| s.to_i } | |
observation_array = observation.split(",").map { |s| s.to_i } | |
# for each key - count how many matches within observation and add result to the output | |
output = [] | |
key_array.each do |k| | |
frequency = 0 | |
observation_array.each do |o| | |
if k == o then frequency += 1 | |
end | |
end | |
output << ("#{k}-#{frequency}") | |
end | |
output | |
end | |
class FrequencyTests < Test::Unit::TestCase | |
def test_count_frequency_of_string_values_five_inputs_three_observations | |
key = "1,2" | |
observation = "1,2,2" | |
calculated = count_frequency_of_string_values(key, observation) | |
assert_equal ["1-1", "2-2"], calculated | |
end | |
def test_count_frequency_of_string_values_nine_inputs_thirty_observations | |
key = "1,2,3,4,5,6,7,8,9" | |
observation = "1,2,3,3,4,4,5,5,6,6,6,7,7,7,7,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9" | |
calculated = count_frequency_of_string_values(key, observation) | |
assert_equal ["1-1", "2-1", "3-2", "4-2", "5-2", "6-3", "7-4", "8-5", "9-10"], calculated | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment