如何使用两个数组创建所有可能的组合 [英] How to create all possible combinations with two arrays
问题描述
我现在的问题是找到形式 a**b a,b <100 它的数字总和是最大的,为此我决定使用数组!我像这样制作了两个数组 a 和 b:
My problem now is to find the number in form a**b a,b < 100 that its, sum of digits is the largest, and to do so I decided to use arrays! I make two arrays a, and b like so:
a = []
b = []
(1..100).map {|n| a << n}
(1..100).map {|n| b << n}
我也决定做一个 sum_of_digits 方法:
and I also decided to make a sum_of_digits method:
class Integer
def sum_of_digits
self.to_s.split("").map {|p| p.to_i}.reduce(:+)
end
end
所以现在我需要构造一个包含 a**b 的所有组合的数组我怎么能这样做?谢谢!
So now I need to construct an array that contains all the combinations of a**b How could I do this? Thanks!
推荐答案
您可以使用 Array#product
方法:
You could use the Array#product
method:
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
定义:
Then, given your Integer#sum_of_digits
definition:
a.product(b).map { |x, y| x ** y }.max_by(&:sum_of_digits)
# => 729
更新:要计算数字的最大数字和 (a ** b),其中 a、b 是小于或等于 100 的自然数,我会这样做:>
Update: to compute the maximum digital sum of the numbers (a ** b), where a, b are natural numbers less or equal to 100, I'd do like this:
Array(1..100)
.repeated_permutation(2)
.map { |a, b| (a ** b).sum_of_digits }
.max
这篇关于如何使用两个数组创建所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!