Morez SA Morez SA - 10 months ago 52
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:
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 :

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

class robot

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

def up
directions[1] += 1

def right
directions[0] += 1

def down
directions[1] -= 1

def left
directions[0] -= 1


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

Answer Source

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

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

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

Key methods: match, Math.sqrt


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