Created
January 28, 2019 16:58
-
-
Save megstang/30b1cce303b39a348e37abe175ef3298 to your computer and use it in GitHub Desktop.
week 2 independent challenge - done in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Robot | |
def initialize() | |
@x = 0 | |
@y = 0 | |
@current_direction = "N" | |
@direction_array = ["N","E","S","W"] | |
end | |
def returns_to_origin(directions) | |
if directions=="" | |
p "true" | |
else | |
directions_array = directions.split('') | |
calculate_movement(directions_array) | |
end | |
end | |
def calculate_movement(directions_array) | |
directions_array.map do |letter| | |
if letter == "G" | |
g_movement | |
elsif letter=="L" || letter== "R" | |
turning_movement(letter) | |
end | |
end | |
if @x == 0 && @y == 0 | |
p "true" | |
else | |
p "false" | |
end | |
end | |
def g_movement | |
if @current_direction == "N" | |
@y+=1 | |
elsif @current_direction =="E" | |
@x+=1 | |
elsif @current_direction == "S" | |
@y-=1 | |
elsif @current_direction == "W" | |
@x-=1 | |
end | |
end | |
# | |
def turning_movement(letter) | |
if letter == "R" | |
index = @direction_array.index(@current_direction) | |
rotated_array = @direction_array.rotate(1) | |
@current_direction = rotated_array[index] | |
else | |
index = @direction_array.index(@current_direction) | |
rotated_array = @direction_array.rotate(-1) | |
@current_direction = rotated_array[index] | |
end | |
end | |
end | |
robot = Robot.new() | |
robot.returns_to_origin("GRGRGRG") | |
robot.returns_to_origin("GRGRLL") | |
robot.returns_to_origin("") | |
robot.returns_to_origin("GRGGRGGRGRGLG") | |
robot.returns_to_origin("GRGRGGLGRGRGRG") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment