如何将数组数组中的值计算为哈希哈希值

时间:2016-12-02 21:17:35

标签: arrays ruby hash

我一直在盯着以下几个数组的数组,以及mergeselectfindmap,{{1}的任意组合等等,还没能帮到我。

我创建了一些丑陋的嵌套循环,但没有任何东西接近Ruby方式。

我有一个数组数组:

flatten

我需要垂直计算值的所有实例,产生这样的散列哈希:

[
["Ja", nil, "Bijna", nil, "Ja"],
["Nee", nil, "Nee", "Ja", "Nee"],
[nil, nil, "Bijna", "Nee", "Nee"],
["Ja", nil, nil, "Nee", "Ja"],
["Bijna", nil, "Bijna", "Nee", "Ja"]
]

请注意,散列中的每个水平线都是数组中垂直的计数。

产生一个新的数组数组(数组)也是可以接受的,尽管我更喜欢散列:

{
{"Ja" => 2, "Nee" => 2, => "Bijna" => 1, "nil" => 1},
{"Ja" => 0, "Nee" => 0, => "Bijna" => 0, "nil" => 5}, 
{"Ja" => 0, "Nee" => 1, => "Bijna" => 3, "nil" => 1}, 
{"Ja" => 0, "Nee" => 1, => "Bijna" => 3, "nil" => 1},
{"Ja" => 3, "Nee" => 2, => "Bijna" => 0, "nil" => 0}
}

3 个答案:

答案 0 :(得分:2)

a成为你的大阵容。

values = a.flatten.uniq
all_values_hash = Hash[values.zip([0] * values.count)]
a.transpose.map do |arr| 
  arr.each_with_object(Hash.new(0)) { |item, hash| hash[item] += 1 }          
end.map { |h| all_values_hash.merge(h) }

答案 1 :(得分:1)

arr = [
  ["Ja",    nil,  "Bijna",    nil,  "Ja"],
  ["Nee",   nil,    "Nee",   "Ja", "Nee"],
  [nil,     nil,  "Bijna",  "Nee", "Nee"],
  ["Ja",    nil,      nil,  "Nee",  "Ja"],
  ["Bijna", nil,  "Bijna",  "Nee",  "Ja"]
]

keys = arr.flatten.uniq
  #=> ["Ja", nil, "Bijna", "Nee"] 
arr.transpose.map { |col| col.each_with_object(keys.product([0]).to_h) { |e,h|
  h[e] += 1 } }
  #=> [{"Ja"=>2, nil=>1, "Bijna"=>1, "Nee"=>1},
  #    {"Ja"=>0, nil=>5, "Bijna"=>0, "Nee"=>0},
  #    {"Ja"=>0, nil=>1, "Bijna"=>3, "Nee"=>1},
  #    {"Ja"=>1, nil=>1, "Bijna"=>0, "Nee"=>3},
  #    {"Ja"=>3, nil=>0, "Bijna"=>0, "Nee"=>2}] 

注意:

arr.transpose
  #=> [["Ja",    "Nee",     nil,  "Ja", "Bijna"],
  #    [nil,       nil,     nil,   nil,     nil],
  #    ["Bijna", "Nee", "Bijna",   nil, "Bijna"],
  #    [nil,      "Ja",   "Nee", "Nee",   "Nee"],
  #    ["Ja",    "Nee",   "Nee",  "Ja",    "Ja"]] 

答案 2 :(得分:1)

与其他解决方案类似,但逻辑相反。我发现它更容易阅读。

keys = my_array.flatten.uniq

final_result = my_array.transpose.map do |array|
 keys.each_with_object(Hash.new) do |key,result|
    result[key] = array.count(key)
 end
end