Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NORTH 0
#define EAST 1
#define SOUTH 2
#define WEST 3
typedef struct
{
int x;
int y;
int dir;
int lost;
} ROBOT;
void turn_right(ROBOT *r);
void turn_left(ROBOT *r);
int go_north(ROBOT *);
int go_east(ROBOT *);
int go_south(ROBOT *);
int go_west(ROBOT *);
typedef struct
{
char ch;
int (*func)(ROBOT *);
} DIRECTION;
DIRECTION dirs[4] =
{
{ 'N', go_north },
{ 'E', go_east },
{ 'S', go_south },
{ 'W', go_west }
};
ROBOT *robots = NULL;
int nrobots = 0;
int maxx, maxy;
int main(void)
{
ROBOT *r;
char buf[100], *p, ch;
fgets(buf, sizeof(buf), stdin);
maxx = atoi(buf);
maxy = atoi(strchr(buf, ' ')+1);
for(;;)
{
robots = realloc(robots, sizeof(ROBOT)*(nrobots+1));
r = &robots[nrobots++];
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf)-1] = '\0';
if(feof(stdin))
{
nrobots--;
break;
}
r->x = atoi(buf);
r->y = atoi((p = strchr(buf, ' ')+1));
ch = *(strchr(p, ' ')+1);
switch(ch)
{
case 'N': r->dir = NORTH; break;
case 'E': r->dir = EAST; break;
case 'S': r->dir = SOUTH; break;
case 'W': r->dir = WEST; break;
}
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf)-1] = '\0';
for(r->lost = 0, p = buf;*p && !r->lost;++p)
{
switch(*p)
{
case 'R': turn_right(r); break;
case 'L': turn_left(r); break;
case 'F': r->lost = dirs[r->dir].func(r); break;
}
}
}
for(r = robots;r-robots < nrobots;++r)
printf("%d %d %c%s\n",
r->x, r->y, dirs[r->dir].ch, r->lost?" LOST":"");
return 0;
}
void turn_right(ROBOT *r)
{
if(++r->dir > 3)
r->dir = 0;
}
void turn_left(ROBOT *r)
{
if(--r->dir < 0)
r->dir = 3;
}
int has_neighbor(ROBOT *robot)
{
ROBOT *r;
for(r = robots;r-robots < nrobots;++r)
if(r != robot && r->x == robot->x && r->y == robot->y)
return 1;
return 0;
}
int go_north(ROBOT *r)
{
if(r->y+1 > maxy)
return !has_neighbor(r);
r->y++;
return 0;
}
int go_east(ROBOT *r)
{
if(r->x+1 > maxx)
return !has_neighbor(r);
r->x++;
return 0;
}
int go_south(ROBOT *r)
{
if(r->y-1 < 0)
return !has_neighbor(r);
r->y--;
return 0;
}
int go_west(ROBOT *r)
{
if(r->x-1 < 0)
return !has_neighbor(r);
r->x--;
return 0;
}
I'm brand new to this site so any information you can give me would be greatly appreciated!
Thank you