advent-of-c-ode/day1/day1.c

145 lines
2.7 KiB
C

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../libs/buffered_reader.h"
#include "../libs/data_structures.h"
int decodeA(const char *str);
int decodeB(const char *str);
char getnumber(const char *str);
list *fl;
list *bl;
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("usage: day1 INPUT_FILE a|b\n");
exit(1);
}
filelines *lines = flines(argv[1]);
if (lines == NULL) {
printf("Failed to read file");
exit(1);
}
if (argv[2][0] == 'b') {
initList(&fl);
initList(&bl);
}
int sum = 0;
for (int i = 0; i < lines->size; i++) {
if (argv[2][0] == 'b') {
sum += decodeB(lines->lines[i]);
} else if (argv[2][0] == 'a') {
sum += decodeA(lines->lines[i]);
}
}
printf("%d\n", sum);
return 0;
}
int decodeB(const char *str) {
int tens = -1;
int ones = -1;
int len = strlen(str);
clears(fl);
clears(bl);
for (int i = 0; i < len; i++) {
int front = str[i];
int back = str[len - 1 - i];
char num;
if (tens < 0) {
if (isalpha(front)) {
pushs(fl, front);
char *fw = contents(fl);
num = getnumber(fw);
free(fw);
if (num > 0) {
tens = num - 48;
}
} else {
tens = front - 48;
}
}
if (ones < 0) {
if (isalpha(back)) {
pushs(bl, back);
char *bw = contentb(bl);
num = getnumber(bw);
free(bw);
if (num > 0) {
ones = num - 48;
}
} else {
ones = back - 48;
}
}
// printf("front %c, tens %d, back %d, ones %d\n", front, tens, back, ones);
}
return tens * 10 + ones;
}
int decodeA(const char *str) {
int tens = -1;
int ones = -1;
int len = strlen(str);
for (int i = 0; i < len; i++) {
int front = str[i];
int back = str[len - 1 - i];
if (!isalpha(front) && tens < 0) {
tens = front - 48;
}
if (!isalpha(back) && ones < 0) {
ones = back - 48;
}
// printf("front %c, tens %d, back %d, ones %d\n", front, tens, back, ones);
}
return tens * 10 + ones;
}
char getnumber(const char *str) {
if (strstr(str, "one") != NULL) {
return '1';
}
if (strstr(str, "two") != NULL) {
return '2';
}
if (strstr(str, "three") != NULL) {
return '3';
}
if (strstr(str, "four") != NULL) {
return '4';
}
if (strstr(str, "five") != NULL) {
return '5';
}
if (strstr(str, "six") != NULL) {
return '6';
}
if (strstr(str, "seven") != NULL) {
return '7';
}
if (strstr(str, "eight") != NULL) {
return '8';
}
if (strstr(str, "nine") != NULL) {
return '9';
}
return -1;
}