aboutsummaryrefslogtreecommitdiff
path: root/2022/01/solve.c
blob: d916f8e69cb65ec8144489b2f2407ec83fd29d2c (plain) (blame)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static int part_one(FILE *fp)
{
	int res = 0;

	char *line = NULL;
	size_t len = 0;

	int current = 0;
	while (getline(&line, &len, fp) != -1) {
		if (line[0] == '\n') {
			if (current > res)
				res = current;
			current = 0;
			continue;
		}

		int num;
		sscanf(line, "%d\n", &num);
		current += num;
	}

	if (line)
		free(line);

	return res;
}

static int sum(int maxes[3])
{
	int s = 0;
	for (int i = 0; i < 3; i++)
		s += maxes[i];
	return s;
}

static void replace_min(int maxes[3], int replace)
{
	int s = 0;
	for (int i = 0; i < 3; i++)
		if (maxes[i] < maxes[s])
			s = i;
	if (replace > maxes[s])
		maxes[s] = replace;
}

static int part_two(FILE *fp)
{
	char *line = NULL;
	size_t len = 0;

	int maxes[3] = { 0 };

	int current = 0;
	while (getline(&line, &len, fp) != -1) {
		if (line[0] == '\n') {
			replace_min(maxes, current);
			current = 0;
			continue;
		}

		int num;
		sscanf(line, "%d\n", &num);
		current += num;
	}
	replace_min(maxes, current);

	if (line)
		free(line);

	return sum(maxes);
}

int main(void)
{
	FILE *fp = fopen("input", "r");
	if (!fp)
		exit(EXIT_FAILURE);

	clock_t tic = clock();
	printf("%d\n", part_one(fp));
	rewind(fp);
	printf("%d\n", part_two(fp));
	clock_t toc = clock();
	printf("TIME: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);

	fclose(fp);
	return 0;
}