advent-of-code/2018/12/d12.c

92 lines
1.9 KiB
C
Raw Permalink Normal View History

2018-12-12 19:57:57 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#define GENERATIONS 20
#define INSIZE 150
typedef struct GrowingArray {
char *content;
int size;
int used;
int bufferLeft;
int bufferRight;
} Array;
Array initArray() {
Array array;
array.size = 10;
array.used = 0;
array.content = malloc(10);
return array;
}
/*
void pushInto(Array array, char element) {
if (array.size == array.used) {
array.size *= 2;
array.content = realloc(array.content, array.size);
}
}
*/
void appendTo(Array array, char element) {
array.content[array.used] = element;
2018-12-13 08:02:51 +01:00
array.used++;
2018-12-12 19:57:57 +01:00
}
// Convert a growth rule (5 chars) to a single byte by creating a bitmask.
// I. e. #..#. -> 10010
char ruleToChar(char *input) {
int currentStep = 0b10000000;
int rule = 0;
for (int i=0; i<5; i++) {
if (input[i] == '#') {
rule += currentStep;
}
currentStep >>= 1;
}
if (input[9] == '#') {
rule |= 1;
}
return rule;
}
int main() {
FILE *inputFile = fopen("input", "r");
2018-12-13 08:02:51 +01:00
printf("hi");
2018-12-12 19:57:57 +01:00
// + 1 for the null byte
char *inString = malloc(INSIZE + 1);
fgets(inString, INSIZE, inputFile);
2018-12-13 08:02:51 +01:00
inString += 15;
2018-12-12 19:57:57 +01:00
char *rawRule = malloc(12);
// discard this as it’s just an empty line
fgets(rawRule, 11, inputFile);
Array rules = initArray();
2018-12-13 08:02:51 +01:00
printf("hi2");
2018-12-12 19:57:57 +01:00
while (fgets(rawRule, 11, inputFile)) {
appendTo(rules, ruleToChar(rawRule));
}
2018-12-13 08:02:51 +01:00
free(inString - 15);
2018-12-12 19:57:57 +01:00
fclose(inputFile);
printf("%d, %c", rules.size, rules.content[0]);
// Theoretically, a plant up to 2 plants away from the current edge can grow.
// As this can happen in either direction, we need to be prepared
// for 4 steps of growth per generation.
char *input = malloc(INSIZE + GENERATIONS * 4);
// Move the start pointer of the array where pot #0 is
input += GENERATIONS * 2;
return 0;
}