aoc

My solutions for the Advent of Code
git clone https://git.tronto.net/aoc
Download | Log | Files | Refs | README

graph.c (1614B)


      1 /* Picture generated with https://csacademy.com/app/graph_editor/ */
      2 
      3 #include <inttypes.h>
      4 #include <stdbool.h>
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <string.h>
      8 
      9 #define N 100
     10 #define ischar(c) (c >= 'a' && c <= 'z')
     11 
     12 typedef struct {
     13 	int nin, nout, in[N], out[N];
     14 	char name[20], outc[N][20];
     15 	bool isff, ison, reg[N];
     16 } node_t;
     17 
     18 char *buf, line[N][N];
     19 bool rx;
     20 int b, r, n;
     21 int64_t npush;
     22 node_t m[N];
     23 
     24 int findm(char *name) {
     25 	for (int k = 0; k < n; k++)
     26 		if (!strcmp(m[k].name, name))
     27 			return k;
     28 	return n;
     29 }
     30 
     31 int main() {
     32 	for (n = 0; (buf = fgets(line[n], N, stdin)) != NULL; n++) {
     33 		if (ischar(*buf)) b = n;
     34 		m[n].isff = *buf == '%';
     35 		if (!ischar(*buf)) buf++;
     36 		for (int i = 0; ischar(*buf); m[n].name[i++] = *(buf++)) ;
     37 		buf += 4;
     38 		for (int i = 0; *buf != '\n'; i++) {
     39 			while (!ischar(*buf)) buf++;
     40 			for (int j = 0; ischar(*buf); m[n].outc[i][j++] = *(buf++)) ;
     41 		}
     42 	}
     43 
     44 	for (int i = 0; i < n; i++) {
     45 		for (int j = 0; m[i].outc[j][0]; j++) {
     46 			int k = findm(m[i].outc[j]);
     47 			m[i].out[m[i].nout++] = k;
     48 			m[k].in[m[k].nin++] = i;
     49 			if (k == n) {
     50 				for (int k = 0; m[i].outc[j][k]; k++)
     51 					m[n].name[k] = m[i].outc[j][k];
     52 				n++;
     53 			}
     54 		}
     55 	}
     56 
     57 	for (int i = 0; i < n; i++)
     58 		if (!strcmp(m[i].name, "rx"))
     59 			r = i;
     60 
     61 /* Print adjacency list
     62 	printf("%d\n", n);
     63 	for (int i = 0; i < n; i++) {
     64 		printf("%d", m[i].nout);
     65 		for (int j = 0; j < m[i].nout; j++)
     66 			printf(" %d", m[i].out[j]);
     67 		printf("\n");
     68 	}
     69 	printf("broadcaster = %d, r = %d\n", b, r);
     70 */
     71 
     72 	for (int i = 0; i < n; i++)
     73 		for (int j = 0; j < m[i].nout; j++)
     74 			printf("%d %d\n", i, m[i].out[j]);
     75 
     76 	return 0;
     77 }