gpt4 book ai didi

ruby - 如何用两个数组创建所有可能的组合

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

我现在的问题是找到 a**b a,b < 100 形式的数字,它的数字总和最大,为此我决定使用数组!我像这样制作两个数组 a 和 b:

a = []
b = []
(1..100).map {|n| a << n}
(1..100).map {|n| b << n}

我还决定制作一个 sum_of_digits 方法:

class Integer
def sum_of_digits
self.to_s.split("").map {|p| p.to_i}.reduce(:+)
end
end

所以现在我需要构造一个数组,其中包含 a**b 的所有组合我怎么能这样做?谢谢!

最佳答案

您可以使用 Array#product方法:

a = [1,2,3]
b = [4,5,6]

a.product(b)
# => [[1, 4], [1, 5], [1, 6], [2, 4], ...]

a.product(b).map { |x, y| x ** y }
# => [1, 1, 1, 16, 32, 64, 81, 243, 729]

然后,根据您的 Integer#sum_of_digits 定义:

a.product(b).map { |x, y| x ** y }.max_by(&:sum_of_digits)
# => 729

更新:要计算数字的最大数字和 (a ** b),其中 a、b 是小于或等于 100 的自然数,我会这样做:

Array(1..100)
.repeated_permutation(2)
.map { |a, b| (a ** b).sum_of_digits }
.max

关于ruby - 如何用两个数组创建所有可能的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20889855/

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