Created
September 22, 2010 13:58
-
-
Save skmetz/591717 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
class Bag < Hash | |
def add(obj) | |
increment_count(obj) | |
end | |
def increment_count(obj) | |
self[obj] = (cnt = self[obj]).nil? ? 1 : cnt + 1 | |
end | |
def total | |
self.values.inject {|tot, cnt| tot + cnt} | |
end | |
def to_s | |
puts "Sum = #{total}" | |
keys.sort.each {|key| puts "#{key} = #{self[key]}"} | |
end | |
end | |
require 'tempfile' | |
def create_data_file(data) | |
file = Tempfile.new('challenge') | |
data.each {|d| file.write(d + "\n")} | |
file.close | |
file | |
end | |
# bag of characters | |
file_of_chars = create_data_file(%w[5 a n 7 4 n 6 1 0 y w a]) | |
bag = Bag.new | |
file_of_chars.open.each {|line| bag.add(line.rstrip)} | |
bag.to_s | |
# Sum = 12 | |
# 0 = 1 | |
# 1 = 1 | |
# 4 = 1 | |
# 5 = 1 | |
# 6 = 1 | |
# 7 = 1 | |
# a = 2 | |
# n = 2 | |
# w = 1 | |
# y = 1 | |
# bag of words | |
file_of_words = create_data_file(%w[Going on vacation yippe on vacation on Sunday]) | |
bag = Bag.new | |
file_of_words.open.each {|line| bag.add(line.rstrip)} | |
bag.to_s | |
# Sum = 8 | |
# Going = 1 | |
# Sunday = 1 | |
# on = 3 | |
# vacation = 2 | |
# yippe = 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment