advent-of-code/2022/1.c

45 lines
1,000 B
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int comp(const void *a, const void *b) {
int n = *(int *)a;
int m = *(int *)b;
return n - m;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "USAGE: %s input_file\n", argv[0]);
return 1;
}
FILE *fd = fopen(argv[1], "r");
if (!fd) {
fprintf(stderr, "Error opening file\n");
return 1;
}
char line[50] = {0};
int idx = 0, elves[1000] = {0};
while (fgets(line, sizeof line / sizeof *line, fd) != NULL) {
if (strlen(line) == 1) {
idx++;
} else {
elves[idx] += atoi(line);
}
}
qsort(elves, idx, sizeof(int), comp);
printf("Elf with the most calories: %d\n", elves[idx - 1]);
printf("Elf with the 2nd most calories: %d\n", elves[idx - 2]);
printf("Elf with the 3rd most calories: %d\n", elves[idx - 3]);
printf("Total: %d\n",
elves[idx - 1] + elves[idx - 2] + elves[idx - 3]);
fclose(fd);
return 0;
}