Added C for zombie

This commit is contained in:
Thomas Muller 2022-12-03 13:41:07 -05:00
parent d75851155b
commit 8030f8a4e4
Signed by: thomas
GPG key ID: AF006EB730564952
4 changed files with 154 additions and 0 deletions

Binary file not shown.

74
day_1/main.c Normal file
View file

@ -0,0 +1,74 @@
#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 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);
}
}
int max = 0;
for(int i = 0; i < list->size; i++) {
if(list->data[i] > max)
max = list->data[i];
printf("%d ", list->data[i]);
}
printf("\n");
printf("max %d\n", max);
fclose(fp);
if(line)
free(line);
list_free(list);
exit(EXIT_SUCCESS);
}

Binary file not shown.

80
day_1/main2.c Normal file
View file

@ -0,0 +1,80 @@
#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);
}