advent2023

Advent of Code 2023 solutions
git clone git://bsandro.tech/advent2023
Log | Files | Refs | LICENSE

commit 5f889027bb1ee05d04ee549c8c05641f21c6e01e
parent 165d0e25020bdbad2c134ae4d0557eb01b8f209a
Author: bsandro <email@bsandro.tech>
Date:   Fri,  8 Dec 2023 18:25:39 +0200

day 08 p2 laptop transition commit

Diffstat:
Mday08/puzzle.c | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
1 file changed, 56 insertions(+), 8 deletions(-)

diff --git a/day08/puzzle.c b/day08/puzzle.c @@ -41,6 +41,20 @@ Node * find_node(Node *first, char name[4]) { return NULL; } +typedef struct Anode { + Node *start; + int znodes[]; +} Anode; + +bool check_z_nodes(Anode *anodes, size_t len) { + for (size_t i=0; i<len; ++i) { + if (anodes[i].start->name[2]!='Z') { + return false; + } + } + return true; +} + void print_nodes(Node *first) { Node *node = first; while (node!=NULL) { @@ -61,6 +75,8 @@ void puzzle(const char *filename, long long *result1, long long *result2) { Node *nodes = NULL; Node *nodes_last = NULL; + Anode *anodes = NULL; + size_t anodes_len = 0; const char *instructions = NULL; while (fgets(buf, STR_LEN, infile) != NULL) { @@ -79,6 +95,14 @@ void puzzle(const char *filename, long long *result1, long long *result2) { if (nodes==NULL) nodes = node; if (nodes_last!=NULL) nodes_last->next = node; nodes_last = node; + + // starting nodes for p.2 + if (node->name[2]=='A') { + ++anodes_len; + anodes = realloc(anodes, anodes_len*sizeof(Anode*)); + anodes[anodes_len-1].start = node; + //anodes[anodes_len-1].znodes = NULL; + } } ++line_num; bzero(buf, STR_LEN); @@ -86,18 +110,15 @@ void puzzle(const char *filename, long long *result1, long long *result2) { int steps = 0; int il = strlen(instructions); + // p.1 Node *n = find_node(nodes, "AAA"); while (1) { char instr = instructions[steps % il]; - Node *nn = NULL; - if (instr=='L') { - nn = find_node(nodes, n->left); - } else if (instr=='R') { - nn = find_node(nodes, n->right); - } else { + if (instr!='L'&&instr!='R') { printf("illegal instruction %c\n", instr); - return; + break; } + Node *nn = find_node(nodes, instr=='L'?n->left:n->right); if (nn==NULL) { printf("node %s was not found\n", instr=='L'?n->left:n->right); break; @@ -114,8 +135,35 @@ void puzzle(const char *filename, long long *result1, long long *result2) { } } + // p.2 + steps = 0; + while (1) { + char instr = instructions[steps % il]; + if (instr!='L'&&instr!='R') { + printf("illegal instruction %c\n", instr); + break; + } + for (size_t i=0; i<anodes_len; ++i) { + Node *n = anodes[i]; + Node *nn = find_node(nodes, instr=='L'?n->left:n->right); + if (nn==NULL) { + printf("node %s was not found\n", instr=='L'?n->left:n->right); + return; + } + anodes[i] = nn; + } + ++steps; + if (check_z_nodes(anodes, anodes_len)) { + *result2 = steps; + break; + } + if (steps==INT_MAX) { + printf("steps overflow\n"); + break; + } + } + // mutiny! ignoring feof/ferror. fclose(infile); - (void)result1; (void)result2; }