93 lines
1.6 KiB
C
93 lines
1.6 KiB
C
#define _POSIX_C_SOURCE 200809L
|
|
|
|
#include <inttypes.h>
|
|
#include <stdbool.h>
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/types.h>
|
|
|
|
enum command {
|
|
UNK = 0,
|
|
FORWARD,
|
|
DOWN,
|
|
UP,
|
|
};
|
|
|
|
struct act {
|
|
enum command cmd;
|
|
uintmax_t cnt;
|
|
};
|
|
|
|
static int
|
|
carray (FILE *f, struct act *res) {
|
|
char * str = NULL;
|
|
size_t bs = 0;
|
|
ssize_t b = getline (&str, &bs, f);
|
|
|
|
if (b == -1) {
|
|
fprintf (stderr, "getline returned a error\n");
|
|
return 1;
|
|
}
|
|
|
|
char *act = strtok (str, " "),
|
|
*cnt = strtok (NULL, "\n");
|
|
|
|
if (act == NULL) {
|
|
fprintf (stderr, "Action is empty.\n");
|
|
return 1;
|
|
}
|
|
|
|
if (strcmp (act, "forward") == 0) {
|
|
res->cmd = FORWARD;
|
|
} else if (strcmp (act, "down") == 0) {
|
|
res->cmd = DOWN;
|
|
} else if (strcmp (act, "up") == 0) {
|
|
res->cmd = UP;
|
|
} else {
|
|
fprintf (stderr, "Line couldn't be parsed.\n");
|
|
return 2;
|
|
}
|
|
res->cnt = strtoumax (cnt, NULL, 10);
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
main (void) {
|
|
struct {
|
|
uintmax_t depth, pos;
|
|
} axis = {
|
|
.depth = 0,
|
|
.pos = 0,
|
|
};
|
|
struct act cur = {0};
|
|
while (carray (stdin, &cur) == 0) {
|
|
switch (cur.cmd) {
|
|
case FORWARD:
|
|
fprintf (stderr, "Added %zu to pos\n", cur.cnt);
|
|
axis.pos += cur.cnt;
|
|
break;
|
|
case DOWN:
|
|
fprintf (stderr, "Added %zu to depth\n", cur.cnt);
|
|
axis.depth += cur.cnt;
|
|
break;
|
|
case UP:
|
|
fprintf (stderr, "Subtracted %zu from depth\n", cur.cnt);
|
|
axis.depth -= cur.cnt;
|
|
break;
|
|
default: {
|
|
fprintf (stderr, "Invalid action was parsed.\n");
|
|
return 1;
|
|
}
|
|
}
|
|
}
|
|
printf ("D: %zu\n"
|
|
"P: %zu\n"
|
|
"C: %zu\n",
|
|
axis.depth,
|
|
axis.pos,
|
|
axis.pos * axis.depth);
|
|
return 0;
|
|
}
|