Morez SA - 1 year ago 108
Python Question

# From Python and learning Ruby coding assistance

I've been learning Python for the last 6 months and have done over a 100 problem exercises and I am now tryinglearn Ruby and solve these exercises in Ruby. This is the exercise I'm having issues with, as I feel as if I'm over complicating things and yet not doing it the right way. This is the exercise:

A robot is moving on a grid and has starting position (0,0). The robot can be directed to move a given number of steps up, down, left, or right.
Write a function that takes in a list of instructions and outputs the distance (in a straight line) the robot is from its starting position. The distance should be rounded to the nearest integer.
The instructions are given as a single array of directions followed by a number of steps to be taken in that direction.

In Python I would start something similar to:

``````import math

pos = [0, 0]

while True:

s = raw_input()
if not s:
break
movement = s.split(" ")
direction = movement[0]
steps = int(movement[1])
if direction == "UP":
pos[0] += steps
elif direction == "DOWN":
pos[0] -= steps
elif direction == "LEFT":
pos[1] -= steps
elif direction == "RIGHT":
pos[1] += steps
else :
pass
``````

And the ruby function that I am creating has the following:

``````class robot

DIRECTIONS = [:up, :left, :down, :right]

def up
directions[1] += 1
end

def right
directions[0] += 1
end

def down
directions[1] -= 1
end

def left
directions[0] -= 1
end

end
``````

What is the simplest and Ruby-way to do this exercise?

With a little help from Pythagoras and q&a's from this similar question I would do something like this:

``````def robot arr
ups    = arr.map {|d| d.match(/UP\s(\d+)/);    \$1.to_i }.inject(:+)
downs  = arr.map {|d| d.match(/DOWN\s(\d+)/);  \$1.to_i }.inject(:+)
rights = arr.map {|d| d.match(/RIGHT\s(\d+)/); \$1.to_i }.inject(:+)
lefts  = arr.map {|d| d.match(/LEFT\s(\d+)/);  \$1.to_i }.inject(:+)

Math.sqrt((rights - lefts)**2 + (ups - downs)**2).to_i
end
``````

Key methods: `match`, `Math.sqrt`

Examples:

``````input = ["UP 5", "DOWN 3", "LEFT 3", "RIGHT 2", "UP 2", "LEFT 1"]
p robot input
#=> 4

input = ["UP 5", "DOWN 1", "LEFT 3", "RIGHT 6"]
p robot input
#=> 5
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download