Skip to content

Instantly share code, notes, and snippets.

@pinkopaque22
Last active March 20, 2016 19:16
Show Gist options
  • Select an option

  • Save pinkopaque22/4b02fd7cd00b462b335e to your computer and use it in GitHub Desktop.

Select an option

Save pinkopaque22/4b02fd7cd00b462b335e to your computer and use it in GitHub Desktop.
Codewars Solution for Most Frequent Item Count in Ruby
MOST FREQUENT ITEM COUNT
Write a program to find count of the most frequent item of an array.
Assume that input is array of integers.
Ex.:
input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
ouptut: 5
Most frequent number in example array is -1. It occures 5 times in input array.
TDD
1.) Test.describe("most_frequent_item_count")
2.) Test.it("works for some examples")
3.) Test.assert_equals(most_frequent_item_count([3, -1, -1]), 2, "didn't work for [3, -1, -1]")
4.) Test.assert_equals(most_frequent_item_count([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]), 5, "didn't work for [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]")
5.) Test.assert_equals(most_frequent_item_count([]), 0, "didn't work for []")
6.) Test.assert_equals(most_frequent_item_count([9]), 1, "didn't work for [9]")
///////////CODE////////////
def most_frequent_item_count(collection)
counts = {}
collection.each do |i|
i = i.to_s.to_sym
counts[i]
if counts.keys.include? i
counts[i] += 1
else
counts[i] = 1
end
end
if counts.values == []
0 #OR use return 0 but not necessary
else
counts.values.sort.last #or you can use counts.values.sort.last || 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment