aoc-2019-c

Advent of Code 2019 Solutions in C
git clone https://git.sinitax.com/sinitax/aoc-2019-c
Log | Files | Refs | README | sfeed.txt

main.c (1952B)


      1#include "aoc.h"
      2#include "util.h"
      3
      4#include <string.h>
      5#include <stdlib.h>
      6#include <stdio.h>
      7
      8int
      9check_pass_1(int *state)
     10{
     11	int i;
     12
     13	for (i = 0; i < 5; i++)
     14		if (state[i] == state[i+1])
     15			break;
     16
     17	if (i != 5) aoc_debug("%i %i %i %i %i %i\n", state[0], state[1],
     18		state[2], state[3], state[4], state[5]);
     19
     20	return i != 5;
     21}
     22
     23int
     24check_pass_2(int *state)
     25{
     26	int i;
     27
     28	for (i = 0; i < 5; i++) {
     29		if (state[i] == state[i+1] && (i == 0 || state[i] != state[i-1])
     30				&& (i == 4 || state[i] != state[i+2]))
     31			break;
     32	}
     33
     34	if (i != 5) aoc_debug("%i %i %i %i %i %i\n", state[0], state[1],
     35		state[2], state[3], state[4], state[5]);
     36
     37	return i != 5;
     38}
     39
     40void
     41count_valid(int *state, int *end, int pinit, int pend,
     42	int index, int *count, int (*check_pass)(int*))
     43{
     44	int i;
     45
     46	if (index == 6) {
     47		*count += check_pass(state);
     48		return;
     49	}
     50
     51	if (index && pinit && state[index-1] > state[index]) {
     52		pinit = 0;
     53		state[index] = state[index-1];
     54	} else if (index && !pinit) {
     55		state[index] = state[index-1];
     56	}
     57
     58	for (i = state[index]; i <= (pend ? end[index] : 9); i++) {
     59		state[index] = i;
     60		count_valid(state, end, pinit, pend && (i == end[index]),
     61			index+1, count, check_pass);
     62	}
     63
     64	state[index] = 0;
     65}
     66
     67void
     68read_state(char *str, int *state)
     69{
     70	int i;
     71
     72	for (i = 0; i < 6; i++)
     73		state[i] = str[i] - '0';
     74}
     75
     76void
     77part1(void)
     78{
     79	int start[6], end[6];
     80	char *tok;
     81	int count;
     82
     83	tok = strchr(aoc.input, '-');
     84	if (!tok) die("main: bad input");
     85	read_state(aoc.input, start);
     86	read_state(tok+1, end);
     87
     88	count = 0;
     89	count_valid(start, end, 1, 1, 0, &count, check_pass_1);
     90
     91	aoc.answer = aprintf("%i", count);
     92	aoc.solution = "966";
     93}
     94
     95void
     96part2(void)
     97{
     98	int start[6], end[6];
     99	char *tok;
    100	int count;
    101
    102	tok = strchr(aoc.input, '-');
    103	if (!tok) die("main: bad input");
    104	read_state(aoc.input, start);
    105	read_state(tok+1, end);
    106
    107	count = 0;
    108	count_valid(start, end, 1, 1, 0, &count, check_pass_2);
    109
    110	aoc.answer = aprintf("%i", count);
    111	aoc.solution = "628";
    112}