1

I need to find the distance between the 2nd and 3rd elements of each nested element so

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)

I'm getting

[[0.0, 1.4142135623730951, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]]

when I need

[[0, 5], [1, 29], [2, 2.82842712474619]]

pythag_theorem works but why isn't map! working for me? Thanks.

3 Answers 3

5
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]]
Sign up to request clarification or add additional context in comments.

Comments

0

Map does the loop for you. You don't need the while loop. You also probably shouldn't modify the the array with map!.

array = [[0, 3, 4], [1, 20, 21], [2, 2, 2]]
array.map { |(_, a, b)| Math.sqrt(a * a + b * b) }
# => [5.0, 29.0, 2.8284271247461903] 

1 Comment

We wrote the answers almost simultaneously :-)
0

This should work for you:

def find_distance(array)
  array.map do |tuple|
    [tuple[0],pythag_theorem(tuple[1],tuple[2])]
  end
end

BTW it is not a good idea to modify a function argument in place.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.