0, "b" => 3}, {"a" =>-6ren">
gpt4 book ai didi

ruby - 数组的所有可能分布,来自一个数字

转载 作者:数据小太阳 更新时间:2023-10-29 06:53:11 25 4
gpt4 key购买 nike

我不太确定如何表达这一点,所以我只是举个例子。

如果我写:

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},
{"a" => 1, "b" => 1, "c" => 0},
{"a" => 1, "b" => 0, "c" => 1},
{"a" => 0, "b" => 2, "c" => 0},
{"a" => 0, "b" => 1, "c" => 1},
{"a" => 0, "b" => 0, "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", "b"], 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}, {"a"=>0, "b"=>2, "c"=>0}, {"a"=>1, "b"=>0, "c"=>1}, {"a"=>1, "b"=>1, "c"=>0}, {"a"=>2, "b"=>0, "c"=>0}]

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

关于ruby - 数组的所有可能分布,来自一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39695024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com