#include "aoc.h" #include "util.h" #include #include #include 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"; }