Computing frequency of terms in a multidimensional array in Ruby
-
25-09-2019 - |
Question
I have an array : keys=[["a","a","b"],["a","b","c"]] I need to find the number of times "a","b","c" occurs in each sub-array of 'keys'.
output could be a hash : ["a"=> [2,1],"b"=>[1,1],"c"=>[0,1]]
Solution
Perhaps not the fastest, but probably among the shortest:
Hash[
keys.flatten.uniq.map{|e|
[e, keys.map{|ar| ar.count(e)}]
}
]
=> {"a"=>[2, 1], "b"=>[1, 1], "c"=>[0, 1]}
or
keys.flatten.uniq.inject({}){|acc,e|
acc.merge({e => keys.map{|ar| ar.count(e)}})
}
Here's a shot at 1.8.6 version:
keys.flatten.uniq.inject({}){|acc,e|
acc[e] = keys.map{|ar|
ar.select{|c| c==e}.size
}
acc
}
But you'd better get that backports gem soon... ;)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow