~srivathsan/aoc2020

21ff372c2fca8fbf2bd34f7134f4aa17ca2055ab — Srivathsan Murali 7 months ago 58d8ac2
d12p2
1 files changed, 108 insertions(+), 0 deletions(-)

A day12p2.c
A day12p2.c => day12p2.c +108 -0
@@ 0,0 1,108 @@
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int peekchar(FILE *fin)
{
    char c = fgetc(fin);
    ungetc(c, fin);
    return c;
}

struct inst_t {
	char action;
	int value;
};

struct status_t {
	int waypt_ns;
	int waypt_ew;
	int ns;
	int ew;
};

void rotate(struct status_t *cur, int angle)
{
	int rotation = (angle/90) % 4;
	for(int i = 0; i < rotation; i++) {
		int temp = cur->waypt_ns * -1;
		cur->waypt_ns = cur->waypt_ew;
		cur->waypt_ew = temp;
	}
}

void move(struct status_t *cur, struct inst_t inst)
{
	switch(inst.action) {
	case 'N':
		cur->waypt_ns += inst.value;
		break;
	case 'S':
		cur->waypt_ns -= inst.value;
		break;
	case 'E':
		cur->waypt_ew += inst.value;
		break;
	case 'W':
		cur->waypt_ew -= inst.value;
		break;
	case 'L':
		rotate(cur, inst.value);
		break;
	case 'R':
		rotate(cur, 360 - inst.value);
		break;
	case 'F':
		cur->ns += cur->waypt_ns * inst.value;
		cur->ew += cur->waypt_ew * inst.value;
		break;
	}
}

void run(struct inst_t insts[1024], int num_insts)
{
	struct status_t cur;
	cur.ns = 0;
	cur.ew = 0;
	cur.waypt_ns = 1;
	cur.waypt_ew = 10;

	for(int i = 0; i < num_insts; i++) {
		move(&cur, insts[i]);
	}

	int manhattan_distance = abs(cur.ns) + abs(cur.ew);
	printf("Part 2: %d\n", manhattan_distance);
}

int main(int argc, char **argv)
{
	if (argc < 2) {
		fprintf(stderr, "usage: %s [file]\n", argv[0]);
		return 1;
	}

	FILE *fin;
	if (argv[1][0] == '-') {
		fin = stdin;
	} else {
		fin = fopen(argv[1], "r");
	}

	if (fin == NULL) {
		fprintf(stderr, "Can't read file: %s\n", argv[1]);
		return 1;
	}

	struct inst_t insts[1024];
	char buffer[8];
	int num_inst = 0;
	while(fgets(&buffer[0], 8, fin)) {
		sscanf(buffer, "%c%d\n", &insts[num_inst].action,
				&insts[num_inst].value);
		num_inst++;
	}

	run(insts, num_inst);
	return 0;
}