【问题标题】:Generating all possible permutations from a hash从散列生成所有可能的排列
【发布时间】:2014-02-20 05:53:33
【问题描述】:

我有一个信息哈希,用于在广告工具中定位用户,如下所示:

{"geo_locations"=>{"countries"=>["US", "GB", "AR"]}, "genders =>[1, 2]}

因此,以上内容将针对这些国家/地区代码和所有性别的所有用户。以上是哈希的简单版本。它也可以包含更多具有自己的值数组的键。

我需要做的是在这个初始散列的后面生成多个散列,这些散列贯穿散列的所有可能组合。因此,通过排列方法运行后,上述哈希的预期输出如下:

{"geo_locations"=>{"countries"=>["US"]}, "genders =>[1]}

{"geo_locations"=>{"countries"=>["GB"]}, "genders =>[1]}

{"geo_locations"=>{"countries"=>["AR"]}, "genders =>[1]}

{"geo_locations"=>{"countries"=>["US"]}, "genders =>[2]}

{"geo_locations"=>{"countries"=>["GB"]}, "genders =>[2]}

{"geo_locations"=>{"countries"=>["AR"]}, "genders =>[2]}

到目前为止,我已经尝试过各种想法,例如遍历散列并将每个键值提取到一个平面数组中,然后应用 Array.product 方法来生成所有可能的排列,但到目前为止我已经死了结尾。笛卡尔积甚至是上述问题的正确解决方案吗?很可能还有另一种我目前不知道的内置 ruby​​ 方法来处理这个问题!

【问题讨论】:

  • Array#product 听起来是正确的方法。
  • 您确定要排列吗?看起来您正在寻找组合。
  • 是什么让1 变得裸露而[2] 和国家被括在括号中?
  • 1 也应该是一个数组 [1]。我现在解决这个问题。格式好像搞砸了。

标签: ruby hash combinations permutation


【解决方案1】:

我愿意

hash = {"geo_locations"=>{"countries"=>["US", "GB", "AR"]}, "genders" =>[1, 2]}
countries = hash["geo_locations"]["countries"]
genders = hash['genders']

array_of_hashes = countries.product(genders).map do |val1,val2|
  {"geo_locations" => { "countries" => val1 }, "genders" => [val2] }
end
array_of_hashes
# => [{"geo_locations"=>{"countries"=>"US"}, "genders"=>[1]},
#     {"geo_locations"=>{"countries"=>"US"}, "genders"=>[2]},
#     {"geo_locations"=>{"countries"=>"GB"}, "genders"=>[1]},
#     {"geo_locations"=>{"countries"=>"GB"}, "genders"=>[2]},
#     {"geo_locations"=>{"countries"=>"AR"}, "genders"=>[1]},
#     {"geo_locations"=>{"countries"=>"AR"}, "genders"=>[2]}]

【讨论】:

  • @steenslag 当然..我实际上做了其他事情,忘了删除它。谢谢指点。。我已经更新了。
猜你喜欢
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多