ruby – 数组的所有可能的分布

前端之家收集整理的这篇文章主要介绍了ruby – 数组的所有可能的分布前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我不太清楚如何表达这一点,所以我只举例.

如果我写:

some_method(["a","b"],3)

我希望它能恢复某种形式

[{"a" => 0,"b" => 3},{"a" => 1,"b" => 2},{"a" => 2,"b" => 1},{"a" => 3,"b" => 0}]

如果我传入

some_method(%w(a b c),2)

预期的回报值应该是

[{"a" => 2,"b" => 0,"c" => 0},"b" => 1,"c" => 1},{"a" => 0,"b" => 2,"c" => 2}]

描述这很难,所以如果你回答这个问题,请提前感谢!

解决方法

这是一种方法
def some_method ary,num
 permutations = (0..num).to_a.repeated_permutation(ary.size).select do |ary| 
    ary.reduce(:+) == num 
 end

 return permutations.map { |a| (ary.zip a).to_h }
end

p some_method ["a",3
#=> [{"a"=>0,"b"=>3},{"a"=>1,"b"=>2},{"a"=>2,"b"=>1},{"a"=>3,"b"=>0}]
p some_method %w(a b c),2
#=> [{"a"=>0,"b"=>0,"c"=>2},{"a"=>0,"b"=>1,"c"=>1},"b"=>2,"c"=>0},"c"=>0}]

根据@seph的提示更新了答案

猜你在找的Ruby相关文章