Skip to content

Instantly share code, notes, and snippets.

@bunnymatic
Last active February 22, 2020 21:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bunnymatic/1648765 to your computer and use it in GitHub Desktop.
Save bunnymatic/1648765 to your computer and use it in GitHub Desktop.
compute histogram in ruby
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