You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
114 lines
2.3 KiB
C
114 lines
2.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define INPUT_FILE ("../input.txt")
|
|
#define ARR_LEN (1000)
|
|
|
|
typedef enum direction
|
|
{
|
|
DIR_FORWARD = 0,
|
|
DIR_UP = 1,
|
|
DIR_DOWN = 2
|
|
}direction;
|
|
|
|
// this is just direction + amount
|
|
typedef struct action_t
|
|
{
|
|
direction dir;
|
|
int amount;
|
|
}action_t;
|
|
|
|
int main(int argc, char** argv)
|
|
{
|
|
int horizontal_pos = 0;
|
|
int depth = 0;
|
|
int aim = 0;
|
|
|
|
FILE* fp = fopen(INPUT_FILE, "r");
|
|
if(fp == NULL)
|
|
{
|
|
printf("Failed to open file for reading...\n");
|
|
exit(-1);
|
|
}
|
|
|
|
size_t len = 0;
|
|
ssize_t rc = 0;
|
|
char* line = NULL;
|
|
char action[12];
|
|
|
|
action_t action_bank[ARR_LEN];
|
|
memset(action_bank, 0, sizeof(action_t) * ARR_LEN);
|
|
int ct = 0;
|
|
while((rc = getline(&line, &len, fp)) > 0)
|
|
{
|
|
memset(action, '\0', 12);
|
|
int amount = 0;
|
|
sscanf(line, "%s %d", action, &amount);
|
|
action_bank[ct].amount = amount;
|
|
if(strcmp(action, "forward") == 0)
|
|
{
|
|
action_bank[ct].dir = DIR_FORWARD;
|
|
horizontal_pos += amount;
|
|
}
|
|
else if(strcmp(action, "up") == 0)
|
|
{
|
|
action_bank[ct].dir = DIR_UP;
|
|
depth -= amount;
|
|
}
|
|
else if(strcmp(action, "down") == 0)
|
|
{
|
|
action_bank[ct].dir = DIR_DOWN;
|
|
depth += amount;
|
|
}
|
|
else
|
|
{
|
|
printf("action didn't match any known actions -- action: %s\n", action);
|
|
exit(-1);
|
|
}
|
|
ct++;
|
|
}
|
|
printf("Part 1\n");
|
|
printf("Horizontal Position: %d\n", horizontal_pos);
|
|
printf("Depth: %d\n", depth);
|
|
printf("calculated course: %d\n", depth * horizontal_pos);
|
|
|
|
// part 2
|
|
horizontal_pos = 0;
|
|
depth = 0;
|
|
for(int ind = 0; ind < ARR_LEN; ind++)
|
|
{
|
|
/* printf(">>>ACTION: %s\tAMOUNT: %d\n", */
|
|
/* action_bank[ind].dir == DIR_FORWARD ? "FORWARD" : */
|
|
/* action_bank[ind].dir == DIR_UP ? "UP" : */
|
|
/* action_bank[ind].dir == DIR_DOWN ? "DOWN" : "UNKNOWN", */
|
|
/* action_bank[ind].amount); */
|
|
if(action_bank[ind].dir == DIR_FORWARD)
|
|
{
|
|
horizontal_pos += action_bank[ind].amount;
|
|
depth += (aim * action_bank[ind].amount);
|
|
}
|
|
else if(action_bank[ind].dir == DIR_UP)
|
|
{
|
|
aim -= action_bank[ind].amount;
|
|
}
|
|
else if(action_bank[ind].dir == DIR_DOWN)
|
|
{
|
|
aim += action_bank[ind].amount;
|
|
}
|
|
else
|
|
{
|
|
printf("Error, dir unknown\n");
|
|
exit(-1);
|
|
}
|
|
|
|
}
|
|
printf("Part 2\n");
|
|
printf("Horizontal Position: %d\n"
|
|
"Depth: %d\n"
|
|
"Aim: %d\n", horizontal_pos, depth, aim);
|
|
|
|
printf("Final Position: %d\n", horizontal_pos * depth);
|
|
return 0;
|
|
}
|