/* * Generates resistor network input files for finite approximations to * the infinite network in xkcd #356, Nerd Sniping. The networks are * even-x-odd size; the size is given by a command-line argument, * which is half the even size and must be at least 1. A * commandline argument of 1 generates a 2x3-node network * * *---*--(*) * | | | * (*)--*---* * * and an argument of 2 generates a 4x5-node network * * *---*---*---*---* * | | | | | * *---*---*--(*)--* * | | | | | * *--(*)--*---*---* * | | | | | * *---*---*---*---* * * etc. * * Node names are of the form X,Y where X and Y are single characters * if the odd dimension is no larger than 36, double characters above * that. (The program errors out if the argument is so large that the * odd dimension exceeds 36*36=1296.) */ #include #include extern const char *__progname; static int n; static void handleargs(int ac, char **av) { unsigned long int nl; char *ep; if (ac != 2) { fprintf(stderr,"Usage: %s half-size\nhalf-size must be 1 to 647.\n",__progname); exit(1); } nl = strtoul(av[1],&ep,0); if ((ep == av[1]) || *ep) { fprintf(stderr,"%s: invalid number `%s'\n",__progname,av[1]); exit(1); } n = nl; if ((n < 0) || (n != nl) || (n > 647)) { fprintf(stderr,"%s: out-of-range argument `%s' (must be 1 to 647)\n",__progname,av[1]); exit(1); } } static void print_n(int v) { static const char digs[36] = "0123456789abcdefghijklmnopqrstuvwxyz"; if (n > 17) { if ((v < 0) || (v >= 36*36)) abort(); printf("%c%c",digs[v/36],digs[v%36]); } else { if ((v < 0) || (v >= 36)) abort(); printf("%c",digs[v]); } } static void print_resistor(int x1, int y1, int x2, int y2) { printf("R "); print_n(x1); printf(","); print_n(y1); printf(" "); print_n(x2); printf(","); print_n(y2); printf(" 1\n"); } static void print_voltage(int x, int y, int v) { printf("V "); print_n(x); printf(","); print_n(y); printf(" %d\n",v); } static void gen(void) { int i; int j; for (i=n+n-1;i>=0;i--) { for (j=n+n;j>=0;j--) { if (j > 0) print_resistor(j-1,i,j,i); if (i > 0) print_resistor(j,i-1,j,i); } } print_voltage(n-1,n,0); print_voltage(n+1,n-1,1); } int main(int ac, char **av) { handleargs(ac,av); gen(); return(0); }