r/badcode • • Dec 07 '20

[deleted by user]

[removed]

20 Upvotes

20 comments sorted by

View all comments

3

u/Mabi19_ Dec 08 '20 edited Dec 10 '20

This submission can be described in two words: Segmentation fault

Yes, it is really easy to crash. (Use a negative rotation)

Written in C; gcc bccc51.c -o bccc51 && ./bccc51 < INPUT FILE

#include <stdio.h>

struct turtle_State;

typedef struct {
	int posX;
	int posY;
	int direction;
} turtle_State;

void TurtleMoveNorth(turtle_State* st, int amount)
{
	st->posY += amount;
}

void TurtleMoveSouth(turtle_State* st, int amount)
{
	st->posY -= amount;
}

void TurtleMoveEast(turtle_State* st, int amount)
{
	st->posX += amount;
}

void TurtleMoveWest(turtle_State* st, int amount)
{
	st->posX -= amount;
}

void (*directions[4])(turtle_State*, int) = {
	TurtleMoveNorth,
	TurtleMoveEast,
	TurtleMoveSouth,
	TurtleMoveWest
};

int main(void) {
	// allocate a large buffer just to be safe
	char buf[80];
	int param;
	turtle_State turtle;
	turtle.posX = 0;
	turtle.posY = 0;
	turtle.direction = 0;
	while (!feof(stdin)) {
		scanf("%s %d", buf, &param);
		// forward
		if (buf[0] == 'f') {
			directions[turtle.direction](&turtle, param);
		}
		if (buf[0] = 'r') {
			turtle.direction = turtle.direction + (param / 90);
			turtle.direction = turtle.direction % 4;
		}
	}
	printf("x = %d, y = %d", turtle.posX, turtle.posY);
	switch (turtle.direction) {
		case 0:
		printf(", direction = north\n");
		break;
		case 1:
		printf(", direction = east\n");
		break;
		case 2:
		printf(", direction = south\n");
		break;
		case 3:
		printf(", direction = west\n");
		break;
	}
}

0

u/[deleted] Dec 15 '20

[deleted] — view deleted comment

1

u/Mabi19_ Dec 15 '20

Um, why did you reply to my comment with this?

1

u/Rabestro Dec 15 '20

Sorry, I would like to post code