This repository has been archived on 2023-12-03. You can view files and clone it, but cannot push or open issues or pull requests.
thomas_2022/day_1/main2.c

81 lines
1.6 KiB
C
Raw Normal View History

2022-12-03 13:41:07 -05:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
size_t size;
size_t max_size;
int *data;
} list_t;
void list_init(list_t **list) {
*list = malloc(sizeof(list_t));
(*list)->size = 0;
(*list)->max_size = 1;
(*list)->data = malloc(sizeof(int));
}
void list_append(list_t *list, int number) {
if(list->size >= list->max_size) {
int *tmp = malloc(list->max_size * 2 * sizeof(int));
memmove(tmp, list->data, list->max_size * sizeof(int));
free(list->data);
list->data = tmp;
list->max_size *= 2;
}
list->data[list->size++] = number;
}
void list_free(list_t *list) {
free(list->data);
free(list);
}
int compare(const void *ap, const void *bp) {
int a = *(int *)ap;
int b = *(int *)bp;
if(a == b) return 0;
if(a > b) return -1;
return 1;
}
int main(int argc, char *argv[]) {
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("input", "r");
if(fp == NULL)
exit(EXIT_FAILURE);
list_t *list;
list_init(&list);
int sum = 0;
while((read = getline(&line, &len, fp)) != -1) {
// printf("%s\n", line);
if(strcmp(line, "\n") == 0) {
list_append(list, sum);
sum = 0;
} else {
sum += atoi(line);
}
}
qsort(list->data, list->size, sizeof(int), compare);
for(int i = 0; i < 3; i++) {
printf("%d ", list->data[i]);
}
printf("\n");
fclose(fp);
if(line)
free(line);
list_free(list);
exit(EXIT_SUCCESS);
}