93 lines
1.9 KiB
C
93 lines
1.9 KiB
C
|
#include <stdlib.h>
|
||
|
#include <stdio.h>
|
||
|
#include <string.h>
|
||
|
#include <stdbool.h>
|
||
|
|
||
|
#define LINES 1000
|
||
|
|
||
|
struct instruction {
|
||
|
char *coord;
|
||
|
struct instruction *next;
|
||
|
};
|
||
|
|
||
|
void addInstruction(struct instruction *start, char *coord)
|
||
|
{
|
||
|
// traverse list until last member
|
||
|
while(start->next) start = start->next;
|
||
|
|
||
|
// allocate and store ptr
|
||
|
start->next = malloc(sizeof(struct instruction));
|
||
|
|
||
|
// store coords in new item
|
||
|
start->next->coord = coord;
|
||
|
start->next->next = 0;
|
||
|
}
|
||
|
|
||
|
bool confirm_numbers(char *start, char *end) {
|
||
|
for (int i = 0; (start[i] >= '0' && start[i] <= '9') || start[i] == ','; i++) {
|
||
|
if (start[i + 1 ] == ')')
|
||
|
return 1;
|
||
|
}
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int parse_numbers(char *string)
|
||
|
{
|
||
|
int i = 0;
|
||
|
int a = 0;
|
||
|
int b = 0;
|
||
|
while (string[i] >= '0' && string[i] <= '9') {
|
||
|
a = a * 10 + string[i] - '0';
|
||
|
i++;
|
||
|
}
|
||
|
// skip comma!
|
||
|
i++;
|
||
|
while (string[i] >= '0' && string[i] <= '9') {
|
||
|
b = b * 10 + string[i] - '0';
|
||
|
i++;
|
||
|
}
|
||
|
return a * b;
|
||
|
}
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
unsigned int sum = 0;
|
||
|
char instructions[32];
|
||
|
|
||
|
FILE *input;
|
||
|
input = fopen("./input", "r");
|
||
|
|
||
|
fseek(input, 0L, SEEK_END);
|
||
|
unsigned int fLen = ftell(input);
|
||
|
char *memory = malloc(fLen * sizeof(char) + 1);
|
||
|
|
||
|
rewind(input);
|
||
|
fread(memory, fLen, sizeof(char), input);
|
||
|
memory[fLen + 1] = '\0';
|
||
|
fclose(input);
|
||
|
|
||
|
// find first instruction start for the list head
|
||
|
char *start = memory;
|
||
|
start = strstr(start, "mul(") + 4;
|
||
|
struct instruction *list = malloc(sizeof(struct instruction));
|
||
|
list->coord = start;
|
||
|
list->next = 0;
|
||
|
|
||
|
// find the rest of the instructions and append to the linked list
|
||
|
while (start = strstr(start, "mul(")) {
|
||
|
start = start + 4;
|
||
|
// confirm format %d,%d)
|
||
|
if (confirm_numbers(start, memory + fLen))
|
||
|
addInstruction(list, start);
|
||
|
}
|
||
|
|
||
|
// from each instruction start, parse and mult numbers
|
||
|
struct instruction *current = list;
|
||
|
while (current) {
|
||
|
sum += parse_numbers(current->coord);
|
||
|
current = current->next;
|
||
|
}
|
||
|
|
||
|
printf("%d\n", sum);
|
||
|
}
|