我在过去的6个月里一直在学习Python,并且已经做了100多个问题练习,现在我正在尝试学习Ruby并用Ruby解决这些练习。这是我有问题的练习,因为我觉得好像我把事情复杂化了,但没有正确的方法。下面是练习:
机器人在网格上移动,起始位置为(0,0)。机器人可以被指示上、下、左或右移动给定数量的台阶。编写一个函数,接收一组指令并输出机器人从起始位置到终点的距离(直线上)。距离应该四舍五入到最接近的整数。这些指令是以一组指令的形式给出的,后面跟着在那个方向上要采取的一些步骤。
在Python中,我会以类似的方式开始:
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
我创建的ruby函数有以下内容:
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
做这个练习最简单的方法是什么?
在毕达哥拉斯和这个类似问题的q&a的帮助下,我将做这样的事情:
def robot arr
ups = arr.map { |d| d.match(/UPs(d+)/); $1.to_i }.inject(:+)
downs = arr.map { |d| d.match(/DOWNs(d+)/); $1.to_i }.inject(:+)
rights = arr.map { |d| d.match(/RIGHTs(d+)/); $1.to_i }.inject(:+)
lefts = arr.map { |d| d.match(/LEFTs(d+)/); $1.to_i }.inject(:+)
Math.hypot(rights - lefts, ups - downs).to_i
end
关键技术与方法:
match
使用regex从每个字符串元素中提取数字。$1
产生最近的match
对象的第一次捕获。Math.hypot
(感谢@steenslag指出这一点)计算斜边,这比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