mirror of
https://codeberg.org/andyscott/advent-of-code.git
synced 2024-11-09 22:00:55 -05:00
Day 1 complete
This commit is contained in:
parent
f38a053bd1
commit
a8851c4f3d
2 changed files with 2295 additions and 0 deletions
45
2022/1.c
Normal file
45
2022/1.c
Normal file
|
@ -0,0 +1,45 @@
|
|||
#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;
|
||||
}
|
2250
2022/1.txt
Normal file
2250
2022/1.txt
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue