next.point = getmove(current.point)
if (next.point is inside bounds) current.point = next.point;
else if (has scent) do nothing;
else { fall over; set scent(current.point); }
Is this correct?
If so, where's my implementation off?
Any help will be greatly appreciated.
- Code: Select all
# include <stdio.h>
# include <stdlib.h>
static const char angles [] = "NESW";
enum bool { false, true };
enum angle { north, east, south, west };
struct point { short x, y; };
struct bot { struct point p; enum angle angle; enum bool lost; };
struct hash { struct hash * next; struct point p; };
static struct point forward (struct bot bot)
{
struct point p = bot.p;
switch (bot.angle)
{
case north: ++ p.y; break;
case east : ++ p.x; break;
case south: -- p.y; break;
case west : -- p.x; break;
}
return p;
}
# define HASHSIZE 31
# define HASH(p) (((p).x * 53 + (p).y) % HASHSIZE)
static struct hash * scents [HASHSIZE];
# define LEFT(b) (((b).angle - 1) % 4)
# define RIGHT(b) (((b).angle + 1) % 4)
int main (void)
{
struct point max;
struct bot bot;
scanf ("%hd %hd", & max.x, & max.y);
while (
3 == scanf (
"%hd %hd %1[NESW]",
& bot.p.x, & bot.p.y, (char *) & bot.angle))
{
int i, ch;
bot.lost = false;
for (i = 0; i < 4; ++i)
if ((char) bot.angle == angles[i])
bot.angle = i;
while (getchar () != '\n');
while ((ch = getchar ()) == 'F' || ch == 'R' || ch == 'L')
if (!bot.lost) switch (ch)
{
case 'F':
{
struct point p = forward (bot);
if (p.x >= 0 && p.x <= max.x && p.y >= 0 && p.y <= max.y)
bot.p = p;
else
{
struct hash * hash = scents[HASH (p)];
for (; hash; hash = hash -> next)
if (hash -> p.x == p.x && hash -> p.y == p.y)
break;
if (hash == NULL) /* if unscented */
{
/* insert new scent */
hash = malloc (sizeof * hash);
hash -> p = p;
hash -> next = scents [HASH (p)];
scents[HASH (p)] = hash;
bot.lost = true;
printf (
"%hd %hd %c LOST\n",
bot.p.x, bot.p.y, angles[bot.angle]);
}
}
}
break;
case 'R': bot.angle = RIGHT (bot); break;
case 'L': bot.angle = LEFT (bot); break;
}
if (!bot.lost)
printf ("%hd %hd %c\n", bot.p.x, bot.p.y, angles[bot.angle]);
}
return 0;
}
-- Jonas

