aboutsummaryrefslogtreecommitdiffstats
path: root/src/04/main.c
blob: 0870dc877d4613ce726e112630be61b8f7c9042e (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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include "aoc.h"
#include "util.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int
check_pass_1(int *state)
{
	int i;

	for (i = 0; i < 5; i++)
		if (state[i] == state[i+1])
			break;

	if (i != 5) aoc_debug("%i %i %i %i %i %i\n", state[0], state[1],
		state[2], state[3], state[4], state[5]);

	return i != 5;
}

int
check_pass_2(int *state)
{
	int i;

	for (i = 0; i < 5; i++) {
		if (state[i] == state[i+1] && (i == 0 || state[i] != state[i-1])
				&& (i == 4 || state[i] != state[i+2]))
			break;
	}

	if (i != 5) aoc_debug("%i %i %i %i %i %i\n", state[0], state[1],
		state[2], state[3], state[4], state[5]);

	return i != 5;
}

void
count_valid(int *state, int *end, int pinit, int pend,
	int index, int *count, int (*check_pass)(int*))
{
	int i;

	if (index == 6) {
		*count += check_pass(state);
		return;
	}

	if (index && pinit && state[index-1] > state[index]) {
		pinit = 0;
		state[index] = state[index-1];
	} else if (index && !pinit) {
		state[index] = state[index-1];
	}

	for (i = state[index]; i <= (pend ? end[index] : 9); i++) {
		state[index] = i;
		count_valid(state, end, pinit, pend && (i == end[index]),
			index+1, count, check_pass);
	}

	state[index] = 0;
}

void
read_state(char *str, int *state)
{
	int i;

	for (i = 0; i < 6; i++)
		state[i] = str[i] - '0';
}

void
part1(void)
{
	int start[6], end[6];
	char *tok;
	int count;

	tok = strchr(aoc.input, '-');
	if (!tok) die("main: bad input");
	read_state(aoc.input, start);
	read_state(tok+1, end);

	count = 0;
	count_valid(start, end, 1, 1, 0, &count, check_pass_1);

	aoc.answer = aprintf("%i", count);
	aoc.solution = "966";
}

void
part2(void)
{
	int start[6], end[6];
	char *tok;
	int count;

	tok = strchr(aoc.input, '-');
	if (!tok) die("main: bad input");
	read_state(aoc.input, start);
	read_state(tok+1, end);

	count = 0;
	count_valid(start, end, 1, 1, 0, &count, check_pass_2);

	aoc.answer = aprintf("%i", count);
	aoc.solution = "628";
}