~jbauer/advent-of-code

ref: b1019419e368d387c5182c277c4e8710b035e446 advent-of-code/main2.c -rw-r--r-- 1.1 KiB
b1019419Jake Bauer Complete Day 1 challenges 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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);
}