我需要找到每个嵌套元素的第二个和第三个元素之间的距离
nested_array = [[0, 3, 4], [1, 20, 21], [2, 2, 2]]
def pythag_theorem(a, b)
c = (a * a) + (b * b)
result = Math.sqrt(c)
result
end
def find_distance(array)
t = 0
while t < array.length
array[t].map! {|x| pythag_theorem(x[1], x[2])}
t += 1
end
array
end
print find_distance(nested_array)
我得到了
[[0.0, 1.4142135623730951, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]]
当我需要的时候
[[0, 5], [1, 29], [2, 2.82842712474619]]
pythag_theorem 可以,但为什么 map 不行!为我工作?谢谢。
最佳答案
a = [[0, 3, 4], [1, 20, 21], [2, 2, 2]]
a.map {|x,y,z| [x, Math.sqrt(y*y + z*z)]}
# => [[0, 5.0], [1, 29.0], [2, 2.82842712474619]]
关于 ruby map !函数和嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9590918/