注意:这个问题提出了一个我已经解决的问题,但是我感觉我的解决方案非常基础,其他像我一样的人会受益于来自更有经验的开发者的讨论。不同的解决问题方法,以及更复杂的方法和算法将非常受欢迎。我认为这是学习如何用Ruby解决对初学者来说相当困难的问题的好地方。
给定一个6x6的二维数组
我们在数组 arr 中定义了一个沙漏,它是指在 arr 的图形表示中,索引值符合以下模式的一组数值:
我们计算以下沙漏数值:
我们最高的沙漏值来自于沙漏:
给定一个6x6的二维数组
arr
:1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
我们在数组 arr 中定义了一个沙漏,它是指在 arr 的图形表示中,索引值符合以下模式的一组数值:
a b c
d
e f g
在arr
中有16个沙漏,沙漏总和是沙漏值的总和。计算每个沙漏的沙漏总和,然后打印出最大的沙漏总和。
例如,给定以下二维数组:
arr = [
[-9, -9, -9, 1, 1, 1],
[ 0, -9, 0, 4, 3, 2],
[-9, -9, -9, 1, 2, 3],
[ 0, 0, 8, 6, 6, 0],
[ 0, 0, 0, -2, 0, 0],
[ 0, 0, 1, 2, 4, 0]
]
我们计算以下沙漏数值:
-63, -34, -9, 12,
-10, 0, 28, 23,
-27, -11, -2, 10,
9, 17, 25, 18
我们最高的沙漏值来自于沙漏:
0 4 3
1
8 6 6
我的解决方案是:
def hourglass_sum(arr)
hourglasses = []
arr.each_with_index do |row, i|
# rescue clause to prevent iterating outside the array
unless arr[i].nil?
arr[i].length.times do |iteration|
# generate n 3x3 arrays
r1 = arr[i][iteration...iteration+3]
r2 = arr[i+1][iteration...iteration+3] if arr[i+1] != nil
r3 = arr[i+2][iteration...iteration+3] if arr[i+2] != nil
# rescue clause to stop creating 3x3 arrays that fall outside given input array
if arr[i+1] != nil && arr[i+2] != nil
# take all values except indices 0 and 5 from the 9 element array
result = r1 + [r2[1]] + r3
hourglasses << result.sum unless result.include? nil
end
end
end
end
p hourglasses.max
end
arr = [[-9, -9, -9, 1, 1, 1], [0, -9, 0, 4, 3, 2], [-9, -9, -9, 1, 2, 3], [0, 0, 8, 6, 6, 0], [0, 0 ,0, -2, 0, 0], [0, 0, 1, 2, 4, 0]]
hourglass_sum(arr)
# => 28
arr
,因为它已经在之前定义过了。 (一般来说,请尽量格式化使读者不必横向滚动。)Ruby 的一个规范是使用 snake case 来命名 Ruby 变量和方法(例如,使用hourglass_sum
而不是hourglassSum
)。当然,您不必遵循这个规范,但是如果不遵循的话,不要惊讶如果您看到一群愤怒的 Ruby 爱好者举着火炬和长叉走向您。 - Cary Swoveland