summaryrefslogtreecommitdiff
path: root/06.c
blob: 44f7dc9d6a46f49af78f5ae2ec6185d0588bf8eb (plain)
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
93
94
95
96
97
98
99
100
101
#include <stdlib.h>
#include <stdio.h>
#include <err.h>
#include <stdbool.h>
#include "input.h"
#include "list.h"

#define INPUT "input/06.txt"
#define INPUT_SIZE 300L
#define EXPECTED1 380758L
#define EXPECTED2 1710623015163L

void part1(struct input_str* input) {
	char* start = input->lines[0];
	char* end = start;
	struct long_list* lanterns = long_list_init(INPUT_SIZE);

	// parse input
	while(*end != '\n') {
		long timer = strtol(start, &end, 0);
		start = end;
		if(*end == ',')
			start++;

		long_list_add(lanterns, timer);
	}

	// time flies
	for(int day = 0; day < 80; day++) {
		size_t init_length = lanterns->length; // we should leave alone the new lanterns
		for(size_t i = 0; i < init_length; i++) {
			long timer = long_list_get(lanterns, i);
			if(timer == 0) {
				timer = 7;
				long_list_add(lanterns, 8);
			}
			timer--;
			long_list_set(lanterns, i, timer);
		}
	}

	CHECK(lanterns->length, EXPECTED1);
	long_list_free(lanterns);
}

void part2(struct input_str* input) {
	// simulating 256 days with the naive approach from part1 is too long and uses up too much memory
	// we need to count lanternfishes based on their timer
	long* lantern_count_by_timer = calloc(9, sizeof(long));
	char* start = input->lines[0];
	char* end = start;

	// parse input
	while(*end != '\n') {
		long timer = strtol(start, &end, 0);
		start = end;
		if(*end == ',')
			start++;

		lantern_count_by_timer[timer]++;
	}

	long* lantern_count_2 = calloc(9, sizeof(long));
	for(int day = 0; day < 256; day++) {
		// simulate the timers decreasing
		for(int i = 8; i > 0; i--) {
			lantern_count_2[i-1] = lantern_count_by_timer[i];
		}
		// handle special cases of lanternfishes with timer 0
		lantern_count_2[8] = lantern_count_by_timer[0];
		lantern_count_2[6] += lantern_count_by_timer[0];

		// switch arrays for the next day
		long* lantern_count_tmp = lantern_count_by_timer;
		lantern_count_by_timer = lantern_count_2;
		lantern_count_2 = lantern_count_tmp;
	}

	// compute total of lanternfish
	long sum = 0;
	for(int i = 0; i < 9; i++)
		sum += lantern_count_by_timer[i];

	free(lantern_count_by_timer);
	free(lantern_count_2);
	CHECK(sum, EXPECTED2);
}

int main() {
	// read input
	struct input_str input;
	input_str_read(&input, INPUT);

	// do stuff
	part1(&input);
	part2(&input);

	// cleanup & exit
	input_str_free(&input);
	return 0;
}