stew

a monorepo of some sort
git clone git://git.nsmpr.xyz/stew.git
Log | Files | Refs

shuf.c (672B)


      1 /*
      2 	Read lines and write them back in random order.
      3 */
      4 
      5 #include <u.h>
      6 #include <libc.h>
      7 #include <bio.h>
      8 typedef struct Line Line;
      9 struct Line {
     10 	char *s;
     11 	Line *next;
     12 };
     13 long i, r, n;
     14 Line start, *lp, *lr;
     15 char *s;
     16 void
     17 main(void)
     18 {
     19 	srand(truerand());
     20 	Biobuf *bp = Bfdopen(0, OREAD);
     21 	lp = &start;
     22 	while ((s = Brdstr(bp, '\n', 0)) != nil) {
     23 		lp->next = malloc(sizeof(Line));
     24 		lp = lp->next;
     25 		if (lp == nil) sysfatal("nil");
     26 		*lp = (Line){s, start.next};
     27 		n++;
     28 	}
     29 	for (i = n; i > 0; i--) {
     30 		r = lnrand(i);
     31 		for (r = lnrand(i); r > 0; r--) {
     32 			lp = lp->next;
     33 			if (lp == nil) sysfatal("nil");
     34 		}
     35 		print("%s", lp->next->s);
     36 		lp->next = lp->next->next;
     37 	}
     38 }