advent2021

Advent of Code 2021 Solutions
git clone git://bsandro.tech/advent2021
Log | Files | Refs

commit 43bfbc12e61030402e89be352b802f9f478f20f0
parent a759041c799d1e2d968b863ca7291a26e7e469b5
Author: bsandro <brian.drosan@gmail.com>
Date:   Sat, 25 Dec 2021 01:44:44 +0200

Day 24, part 1+2 solution made by hand but the puzzle was not fun anyway

Diffstat:
Mday24/puzzle.c | 39+++++++++++++++++++++++----------------
1 file changed, 23 insertions(+), 16 deletions(-)

diff --git a/day24/puzzle.c b/day24/puzzle.c @@ -41,6 +41,7 @@ int exec_eql(struct cmd_t *cmd, int (*registers)[5]); int read_input(struct input_t *input); struct input_t make_input(uint64_t number); bool valid_input(struct input_t *input); +bool validate_number(struct array_t *commands, uint64_t num); void puzzle(const char *filename, long long *result1, long long *result2) { FILE *infile = fopen(filename, "r"); @@ -58,28 +59,34 @@ void puzzle(const char *filename, long long *result1, long long *result2) { bzero(buf, STR_LEN); } - for (uint64_t i = 99999999999999; i >= 11111111111111; --i) { - struct input_t input = make_input(i); - if (valid_input(&input)) { - int registers[5] = {0}; - for (size_t k = 0; k < commands.count; ++k) { - struct cmd_t *cmd = &((struct cmd_t *)commands.data)[k]; - exec_cmd(cmd, &registers, &input); - } - input.current = 0; - if (registers[4] == 0) { - *result1 = i; - break; - } - } + uint64_t max_num = 94992992796199; + uint64_t min_num = 11931881141161; + + if (validate_number(&commands, max_num)) { + *result1 = max_num; } - *result2 = 0; + if (validate_number(&commands, min_num)) { + *result2 = min_num; + } // mutiny! ignoring feof/ferror. fclose(infile); } +bool validate_number(struct array_t *commands, uint64_t num) { + struct input_t input = make_input(num); + if (valid_input(&input)) { + int registers[5] = {0}; + for (size_t k = 0; k < commands->count; ++k) { + struct cmd_t *cmd = &((struct cmd_t *)commands->data)[k]; + exec_cmd(cmd, &registers, &input); + } + return registers[4] == 0; + } + return false; +} + void parse_command(struct array_t *commands, char *str) { assert(commands != NULL); assert(str != NULL); @@ -204,6 +211,6 @@ int exec_mod(struct cmd_t *cmd, int (*registers)[5]) { int exec_eql(struct cmd_t *cmd, int (*registers)[5]) { assert(cmd != NULL); int r = cmd->reg2 > 0 ? (*registers)[cmd->reg2] : cmd->op2; - (*registers)[cmd->reg1] = (*registers)[cmd->reg1] == r ? 1 : 0; + (*registers)[cmd->reg1] = ((*registers)[cmd->reg1] == r) ? 1 : 0; return (*registers)[cmd->reg1]; }