Created
April 22, 2015 16:26
-
-
Save silverweed/0cd26dbf2142fb7c60a9 to your computer and use it in GitHub Desktop.
This file contains 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
# http://www.reddit.com/r/dailyprogrammer/comments/32vlg8/20150417_challenge_210_hard_loopy_robots/ | |
type Point{T <: Real} | |
x :: T | |
y :: T | |
end | |
const NORTH = uint8(0) | |
const EAST = uint8(1) | |
const SOUTH = uint8(2) | |
const WEST = uint8(3) | |
const RIGHT = uint8(4) | |
const LEFT = uint8(5) | |
typealias Direction Uint8 | |
type Robot | |
pt :: Point{Int} | |
dir :: Direction | |
instrcount :: Uint | |
end | |
Robot(pt, dir) = Robot(pt, dir, 0) | |
immutable RobotState | |
pt :: Point{Int} | |
dir :: Direction | |
end | |
RobotState(robot :: Robot) = RobotState(deepcopy(robot.pt), robot.dir) | |
# ENTRYPOINT | |
function main(args) | |
command = args[1] | |
robot = Robot(Point(0, 0), NORTH) | |
initialstate = RobotState(robot) | |
checkloop!(robot, command, initialstate) | |
end | |
function checkloop!(robot :: Robot, command :: String, initialstate :: RobotState) | |
robotexecute!(robot, command, initialstate) | |
cycles = if initialstate.pt.x == robot.pt.x && | |
initialstate.pt.y == robot.pt.y && | |
initialstate.dir == robot.dir | |
1 | |
elseif initialstate.dir == robot.dir | |
0 | |
elseif initialstate.dir == (robot.dir + uint8(2)) % 4 | |
2 | |
else | |
4 | |
end | |
if cycles == 0 | |
println("No loop detected.") | |
else | |
println("Entered in a loop after $cycles instructions!") | |
end | |
end | |
function robotexecute!(robot :: Robot, command :: String, initialstate :: RobotState) | |
for i = 1:length(command) | |
if command[i] == 'S' | |
robotstep!(robot) | |
elseif command[i] == 'R' | |
robotturn!(robot, RIGHT) | |
elseif command[i] == 'L' | |
robotturn!(robot, LEFT) | |
else | |
error("Invalid command: $(command[i])") | |
end | |
robot.instrcount += 1 | |
end | |
end | |
function robotstep!(robot :: Robot) | |
if robot.dir == NORTH | |
robot.pt.y += 1 | |
elseif robot.dir == EAST | |
robot.pt.x += 1 | |
elseif robot.dir == SOUTH | |
robot.pt.y -= 1 | |
elseif robot.dir == WEST | |
robot.pt.x -= 1 | |
else | |
error("Invalid robot direction: $(robot.dir)") | |
end | |
end | |
function robotturn!(robot :: Robot, dir :: Direction) | |
if dir == RIGHT | |
robot.dir = (robot.dir + uint8(1)) % 4 | |
elseif dir == LEFT | |
robot.dir = (robot.dir - uint8(1)) % 4 | |
else | |
error("Invalid turn direction: $dir") | |
end | |
end | |
main(ARGS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment