93 lines
2.1 KiB
C
93 lines
2.1 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define LINE_MAX_LENGTH 256
|
|
#define MAX_VALUE_PER_HISTORY 64
|
|
|
|
int extrapolate(int history[], int history_num);
|
|
int extrapolate_backwards(int history[], int history_num);
|
|
|
|
int main() {
|
|
char *p, *buf, c;
|
|
|
|
buf = (char *)malloc(LINE_MAX_LENGTH);
|
|
memset(buf, 0, LINE_MAX_LENGTH);
|
|
p = buf;
|
|
|
|
int part1 = 0, part2 = 0;
|
|
|
|
while ((c = getchar()) != EOF) {
|
|
*p++ = c;
|
|
if (c == '\n') {
|
|
int history[MAX_VALUE_PER_HISTORY], history_num = 0;
|
|
p = buf;
|
|
|
|
while (*p != '\0') {
|
|
sscanf(p, "%i", &history[history_num]);
|
|
history_num++;
|
|
while(*p != ' ' && *p != '\n') p++;
|
|
p++;
|
|
}
|
|
|
|
part1 += extrapolate(history, history_num);
|
|
part2 += extrapolate_backwards(history, history_num);
|
|
|
|
memset(buf, 0, LINE_MAX_LENGTH);
|
|
p = buf;
|
|
}
|
|
}
|
|
|
|
printf("%i\n", part1);
|
|
printf("%i\n", part2);
|
|
free(buf);
|
|
}
|
|
|
|
int extrapolate(int history[], int history_num) {
|
|
int zeros = 1;
|
|
for (int i = 0; i < history_num; i++) {
|
|
if (history[i] != 0) {
|
|
zeros = 0;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (zeros) {
|
|
return 0;
|
|
}
|
|
|
|
int *new_history = (int*)malloc((history_num - 1) * sizeof(int));
|
|
|
|
for (int i = 0; i < history_num - 1; i++) {
|
|
new_history[i] = history[i+1] - history[i];
|
|
}
|
|
|
|
int result = extrapolate(new_history, history_num - 1) + history[history_num - 1];
|
|
free(new_history);
|
|
return result;
|
|
}
|
|
|
|
int extrapolate_backwards(int history[], int history_num) {
|
|
int zeros = 1;
|
|
for (int i = 0; i < history_num; i++) {
|
|
if (history[i] != 0) {
|
|
zeros = 0;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (zeros) {
|
|
return 0;
|
|
}
|
|
|
|
int *new_history = (int*)malloc((history_num - 1) * sizeof(int));
|
|
|
|
for (int i = 0; i < history_num - 1; i++) {
|
|
new_history[i] = history[i+1] - history[i];
|
|
}
|
|
|
|
int result = history[0] - extrapolate_backwards(new_history, history_num - 1);
|
|
free(new_history);
|
|
return result;
|
|
}
|