This can be cleaned up quite a lot, but it should be a good framework to understand the concepts. All we're basically doing is saving every move, and then simply backtracking it.
#include <stdio.h>
#define MAX_STEPS 256
enum CARDINAL_DIRECTIONS { N = 0, W, S, E };
struct _s_robot {
int x;
int y;
int orientation;
int step;
int x_history[MAX_STEPS];
int y_history[MAX_STEPS];
int turn_history[MAX_STEPS];
} MY_LITTLE_ROBOT = {0, 0, 0, 0, {0}, {0}, {0}};
void robot_go() {
switch(MY_LITTLE_ROBOT.orientation) {
case N:
++MY_LITTLE_ROBOT.y;
break;
case W:
--MY_LITTLE_ROBOT.x;
break;
case S:
--MY_LITTLE_ROBOT.y;
break;
case E:
++MY_LITTLE_ROBOT.x;
break;
}
MY_LITTLE_ROBOT.x_history[MY_LITTLE_ROBOT.step] = MY_LITTLE_ROBOT.x;
MY_LITTLE_ROBOT.y_history[MY_LITTLE_ROBOT.step] = MY_LITTLE_ROBOT.y;
MY_LITTLE_ROBOT.turn_history[MY_LITTLE_ROBOT.step] = MY_LITTLE_ROBOT.orientation;
++MY_LITTLE_ROBOT.step;
}
void robot_change_orientation(int _orientation) {
MY_LITTLE_ROBOT.orientation = _orientation;
}
void robot_reverse_orientation(int _orientation) {
if (_orientation == N) MY_LITTLE_ROBOT.orientation = S;
else if (_orientation == W) MY_LITTLE_ROBOT.orientation = E;
else if (_orientation == S) MY_LITTLE_ROBOT.orientation = N;
else if (_orientation == E) MY_LITTLE_ROBOT.orientation = W;
}
void robot_backtrack() {
int i;
printf("MY_LITTLE_ROBOT wants to turn around, currently at: %i, %i\n", MY_LITTLE_ROBOT.x, MY_LITTLE_ROBOT.y);
robot_reverse_orientation(MY_LITTLE_ROBOT.orientation);
for (i = MY_LITTLE_ROBOT.step-1; i >= 0; --i) {
printf("Robot is @ %i, %i, with an orientation of: %i \n", MY_LITTLE_ROBOT.x, MY_LITTLE_ROBOT.y, MY_LITTLE_ROBOT.orientation );
robot_reverse_orientation(MY_LITTLE_ROBOT.turn_history[i]);
robot_go();
}
}
void dump_history() {
int i;
for (i = MY_LITTLE_ROBOT.step-1; i >= 0; --i) {
printf("Robot is @ %i, %i, with an orientation of: %i \n", MY_LITTLE_ROBOT.x_history[i], MY_LITTLE_ROBOT.y_history[i], MY_LITTLE_ROBOT.turn_history[i] );
}
}
int main() {
printf("***START: Robot is @ %i, %i\n", MY_LITTLE_ROBOT.x, MY_LITTLE_ROBOT.y);
robot_go();
robot_go();
robot_go();
robot_change_orientation(S);
robot_go();
robot_go();
robot_change_orientation(W);
robot_go();
robot_go();
robot_go();
robot_change_orientation(N);
robot_go();
dump_history();
robot_backtrack();
printf("***FINISH: Robot is @ %i, %i\n", MY_LITTLE_ROBOT.x, MY_LITTLE_ROBOT.y);
return 0;
}
To use the robot over and over again, you may have to reset all travel history after a backtrack, which should be somewhat trivial. I purposely avoided malloc
s and other confusing aspects of making the program actually useful for the sake of verbosity and simplicity. Hopefully it helps.
I also assumed you didn't want a true path-finding algorithm (such as A*), because that's a different ballgame altogether.