~jbauer/advent-of-code

b1019419e368d387c5182c277c4e8710b035e446 — Jake Bauer 6 months ago f2dbf28 d1
Complete Day 1 challenges
3 files changed, 117 insertions(+), 0 deletions(-)

M README.md
A main1.c
A main2.c
M README.md => README.md +3 -0
@@ 3,3 3,6 @@
Each day is tagged with a git tag.

Compile the code with `cc main.c` and run with `./a.out`.

Some days may have multiple challenges, the first would be in `main1.c`, the
second in `main2.c` and so on.

A main1.c => main1.c +46 -0
@@ 0,0 1,46 @@
#include <stdio.h>
#include <stdlib.h>

FILE *
openInputFile(void)
{
	FILE *fp = fopen("input.txt","r");
	if (fp == NULL)
	{
		printf("Could not open file: input.txt\n");
		exit(EXIT_FAILURE);
	}
	return fp;
}

int
main(void)
{
	char *line = NULL;
	int increases = 0;
	int currentValue = 0;
	int previousValue = -1;
	size_t len = 0;
	ssize_t read;

	FILE *fp = openInputFile();

	while ((read = getline(&line, &len, fp)) != -1)
	{
		if (previousValue < 0)
			previousValue = atoi(line);

		currentValue = atoi(line);

		if (currentValue > previousValue)
			increases++;

		previousValue = currentValue;
	}

	fclose(fp);
	if (line)
		free(line);
	printf("%d\n", increases);
	exit(EXIT_SUCCESS);
}

A main2.c => main2.c +68 -0
@@ 0,0 1,68 @@
#include <stdio.h>
#include <stdlib.h>

#define ARR_SIZE 3

FILE *
openInputFile(void)
{
	FILE *fp = fopen("input.txt","r");
	if (fp == NULL)
	{
		printf("Could not open file: input.txt\n");
		exit(EXIT_FAILURE);
	}
	return fp;
}

int
sumArray(int *array, int size)
{
	int sum = 0;
	for (int i = 0; i < size; i++)
		sum += array[i];
	return sum;
}

int
main(void)
{
	FILE *fp = openInputFile();
	int increases = 0;

	int array[ARR_SIZE] = { 0 };
	int arrayPosition = 0;
	int currentSum = 0;
	int previousSum = 0;
	int firstFill = 1;

	char *line = NULL;
	size_t len = 0;
	ssize_t read;
	while ((read = getline(&line, &len, fp)) != -1)
	{
		if (arrayPosition == ARR_SIZE) {
			if (firstFill)
				previousSum = currentSum;
			firstFill = 0;
			arrayPosition = 0;
		}

		currentSum = sumArray(array, ARR_SIZE);
		array[arrayPosition++] = atoi(line);

		// Don't do comparisons until we've filled the array
		if (firstFill)
			continue;

		if (currentSum > previousSum)
			increases++;
		previousSum = currentSum;
	}

	fclose(fp);
	if (line)
		free(line);
	printf("%d\n", increases);
	exit(EXIT_SUCCESS);
}