day 2 part 1
This commit is contained in:
parent
16a5fc040f
commit
24d29efa19
1 changed files with 72 additions and 0 deletions
72
day_2/1.c
Normal file
72
day_2/1.c
Normal file
|
@ -0,0 +1,72 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct levels {
|
||||
size_t mem_size;
|
||||
size_t size;
|
||||
unsigned int *data;
|
||||
} levels_t;
|
||||
|
||||
int main(void) {
|
||||
FILE *fp = fopen("input", "r");
|
||||
|
||||
if (fp == NULL) {
|
||||
perror("input");
|
||||
return 1;
|
||||
}
|
||||
|
||||
char *line = NULL;
|
||||
size_t size;
|
||||
|
||||
levels_t levels;
|
||||
levels.mem_size = 10;
|
||||
levels.size = 0;
|
||||
levels.data = malloc(sizeof(unsigned int) * levels.mem_size);
|
||||
|
||||
unsigned int sum = 0;
|
||||
while (getline(&line, &size, fp) > 0) {
|
||||
char *next = strtok(line, " ");
|
||||
|
||||
while (next != NULL) {
|
||||
if (levels.size >= levels.mem_size) {
|
||||
levels.mem_size *= 2;
|
||||
levels.data =
|
||||
realloc(levels.data, levels.mem_size * sizeof(unsigned int));
|
||||
}
|
||||
|
||||
sscanf(next, "%u", &levels.data[levels.size]);
|
||||
levels.size++;
|
||||
|
||||
next = strtok(NULL, " ");
|
||||
}
|
||||
|
||||
bool safe = true;
|
||||
int diff = levels.data[1] - levels.data[0];
|
||||
int increasing = diff > 0 ? 1 : -1;
|
||||
for (int i = 1; i < levels.size; i++) {
|
||||
diff = increasing * (levels.data[i] - levels.data[i - 1]);
|
||||
|
||||
if (diff < 1 || diff > 3) {
|
||||
safe = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (safe) {
|
||||
sum++;
|
||||
}
|
||||
|
||||
levels.size = 0;
|
||||
}
|
||||
|
||||
free(line);
|
||||
free(levels.data);
|
||||
|
||||
printf("%u\n", sum);
|
||||
|
||||
fclose(fp);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue