~jbauer/advent-of-code

9149ffedaf4231a9431cf7102332093c3c5dfb04 — Jake Bauer 6 months ago b101941 d2
Complete Day 2 challenges
2 files changed, 38 insertions(+), 50 deletions(-)

M main1.c
M main2.c
M main1.c => main1.c +19 -16
@@ 1,5 1,6 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *
openInputFile(void)


@@ 16,31 17,33 @@ openInputFile(void)
int
main(void)
{
	FILE *fp = openInputFile();

	int position = 0;
	int depth = 0;

	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;
		char *direction = strtok(line, " ");
		int magnitude = atoi(strtok(NULL, " "));

		if (strcmp("forward", direction) == 0)
			position += magnitude;
		else if (strcmp ("down", direction) == 0)
			depth += magnitude;
		else
			depth -= magnitude;
	}

	printf("Final position: %d\n", position);
	printf("Final depth: %d\n", depth);
	printf("Product: %d\n", position * depth);

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

M main2.c => main2.c +19 -34
@@ 1,7 1,6 @@
#include <stdio.h>
#include <stdlib.h>

#define ARR_SIZE 3
#include <string.h>

FILE *
openInputFile(void)


@@ 16,53 15,39 @@ openInputFile(void)
}

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;
	int position = 0;
	int depth = 0;
	int aim = 0;

	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;
		char *direction = strtok(line, " ");
		int magnitude = atoi(strtok(NULL, " "));

		if (currentSum > previousSum)
			increases++;
		previousSum = currentSum;
		if (strcmp("forward", direction) == 0)
		{
			position += magnitude;
			depth += aim * magnitude;
		}
		else if (strcmp ("down", direction) == 0)
			aim += magnitude;
		else
			aim -= magnitude;
	}

	printf("Final position: %d\n", position);
	printf("Final depth: %d\n", depth);
	printf("Product: %d\n", position * depth);

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