Login
|
Signup
langref.org
-
ruby
add..
all
clojure
cpp
csharp
erlang
fantom
fsharp
go
groovy
haskell
java
ocaml
perl
php
python
scala
Home
All
Solved
Unsolved
Strings
Numbers
Regex
Lists
Maps
Structure
Files
Dates
OOP
Networking
XML
Algorithms
Misc
Parallel
View Problem
Maps
Algorithms
Create a histogram map from a list
Given the list
[a,b,a,c,b,b]
, produce a map
{a:2, b:3, c:1}
which contains the count of each unique item in the list
ruby
histogram = {}
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
list=['a','b','a','c','b','b']
histogram = {}
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
p histogram # {"a"=>2, "b"=>3, "c"=>1}
ruby
1.9
list = %w{a b a c b b}
histogram = list.each_with_object(Hash.new(0)) do |item, hash|
hash[item] += 1
end
p histogram # => {"a"=>2, "b"=>3, "c"=>1}
list = %w{a b a c b b}
histogram = list.each_with_object(Hash.new(0)) do |item, hash|
hash[item] += 1
end
p histogram # => {"a"=>2, "b"=>3, "c"=>1}
ruby
list.inject(Hash.new(0)) {|h, item| h[item] += 1; h}
list.inject(Hash.new(0)) {|h, item| h[item] += 1; h}
Submit a new solution for
ruby
There are 36 other solutions in
additional
languages (
clojure
,
cpp
,
csharp
,
erlang
...)