编辑:@PinnyM 正确地指出我应该使用 Array#repeated_permutation 而不是 Array#permutation,因为后者不包括对 [i,i]。为了多样性,我没有进行更正,而是将a.permutation(2).to_a替换为a.permutation(2).to_a + a.zip(a)。
a = (1..100).to_a
(a.permutation(2).to_a + a.zip(a)).map {|i,j| (i ** j).sum_of_digits}.max
# => 972
获胜者是:
(a.permutation(2).to_a + a.zip(a)).map \
{|i,j| [i, j, (i ** j).sum_of_digits]}.max_by(&:last)
# => [99, 95, 972] (99**95).sum_of_digits # => 972
如果是i <= 3,而不是i <= 100,则执行以下步骤:
a = (1..3).to_a # => [1,2,3]
b = a.permutation(2) # => #<Enumerator: [1, 2, 3]:permutation(2)>
c = b.to_a # => [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
d = a.zip(a) # => [[1, 1], [2, 2], [3, 3]]
e = c + d # => [[1,2], [1,3], [2,1], [2,3], [3,1], [3,2], [1,1], [2,2], [3,3]]
f = e.map {|i,j| (i ** j).sum_of_digits} # => [1, 1, 2, 8, 3, 9, 1, 4, 9]
f.max # => 9
在 Ruby 2.0 中,您可以通过将 class Integer 替换为 refine Integer do 来将 sum_of_digits 方法的使用限制在当前上下文(例如类)中。如果您认为您可能想在其他地方使用该方法,您可以将它放在一个模块中,并在需要的地方 include 模块。