Ruby数组中的基本方向

时间:2015-10-13 19:54:55

标签: ruby

我正在尝试创建一个程序来跟踪一个人左右转动时的方位(例如,如果他们面向北方并向左转,它们将面向北方。)我写的是一个数组,两种方式都有效。到目前为止,这是我的代码:

puts "What is your initial bearing?"
bearing = gets.chomp

puts "And what turns do you want to make?"
turn_list = gets.chomp

cardinal_directions = ["N", "E", "S", "W"]

position = cardinal_directions.index(bearing)
turn_list.each |direction|
case "L"
    position += 1
case "R" 
    position -= 1
end

但是有一个明显的问题。说我的人面向西方,想要向右转。我怎么能告诉它从索引3到索引0?或者如果他们在北方并且想要左转?

请原谅蹩脚的代码和格式,我是新手。非常感谢你的帮助!

3 个答案:

答案 0 :(得分:3)

由于您有4种可能的选项,当变量除以4时,您可以使用模运算(即得到余数):

case turn_list
when "R"
    position = (position + 1)%4
when "L" 
    position = (position - 1)%4
end

%符号是模运算符,当两个数字被分割时,它将为您提供余数。这应该给你你想要的答案。例如,如果你在位置3(西)并向右转,你加1并除以4得到余数,即0(北)。

(我编辑了案例“R”和“L”因为我认为你在问题中将它们标记为倒退。)

答案 1 :(得分:2)

你可以使用Array#rotate!传递1(或者没有,因为1是默认参数)向右移动,-1向左移动,始终保持原始位置:

cardinal_directions = ["N", "E", "S", "W"]
# => ["N", "E", "S", "W"] 
position = cardinal_directions.index('S')
# => 2 
cardinal_directions.rotate!(1)
# => ["E", "S", "W", "N"] 
cardinal_directions[position]
# => "W" 
cardinal_directions.rotate!(1)
# => ["S", "W", "N", "E"] 
cardinal_directions[position]
# => "N" 
cardinal_directions.rotate!(1)
# => ["W", "N", "E", "S"] 
cardinal_directions[position]
# => "E" 
cardinal_directions.rotate!(-1)
# => ["S", "W", "N", "E"] 
cardinal_directions[position]
# => "N" 
cardinal_directions.rotate!(-1)
# => ["E", "S", "W", "N"] 
cardinal_directions[position]
# => "W" 

答案 2 :(得分:1)

我建议你上一堂课来跟踪每个人的承受情况:

class Wanderers
  attr_accessor :name, :bearing

  def initialize(name, initial_bearing, at_south_pole = false)
    @name = name
    @bearing = at_south_pole ? :north : initial_bearing
    @at_south_pole = at_south_pole
  end

  def turn_left
    return :north if @at_south_pole
    @bearing = 
    case @bearing
    when :north  then :west
    when :west   then :south
    when :south  then :east
    when :east   then :north
    end
  end

  def turn_right
    return :north if @at_south_pole
    @bearing = 
    case @bearing
    when :north  then :east
    when :east   then :south
    when :south  then :west
    when :west   then :north
    end
  end
end

然后:

hector = Wanderers.new "Hector", :east
hector.turn_right #=> :south 
hector.turn_right #=> :west 
hector.turn_right #=> :north 
hector.turn_right #=> :east 
hector.turn_left  #=> :north 
hector.bearing    #=> :north 

lola = Wanderers.new "Lola", :north, true
lola.turn_right   #=> :north 
lola.turn_right   #=> :north 
lola.turn_left    #=> :north 
lola.bearing      #=> :north