Last active
February 22, 2020 21:03
-
-
Save bunnymatic/1648765 to your computer and use it in GitHub Desktop.
compute histogram in ruby
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
def tally inp; hash = Hash.new(0); inp.each {|k,v| hash[k] +=v}; hash; end | |
def histogram inp; hash = Hash.new(0); inp.each {|v| hash[v]+=1}; hash; end | |
def histogram2 inp; Hash[*inp.group_by{ |v| v }.flat_map{ |k, v| [k, v.size] }] end | |
def test_tally | |
tally([['a',1],['b',1],['a',1],['c',1],['a',3], ['c',1]]) == {'a'=>5, 'b'=>1, 'c'=>2} | |
end | |
def test_histogram | |
histogram(['a','b','a','c','a', 'c']) == {'a'=>3, 'b'=>1, 'c'=>2} | |
end | |
def test_histogram2 | |
histogram2(['a','b','a','c','a', 'c']) == {'a'=>3, 'b'=>1, 'c'=>2} | |
end | |
puts "Tally %s" % test_tally | |
puts "Hist %s" % test_histogram | |
puts "Hist2 %s" % test_histogram2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment