]> mj.ucw.cz Git - misc.git/blob - randomize.c
Merge branch 'master' of git+ssh://git.ucw.cz/home/mj/GIT/misc
[misc.git] / randomize.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/time.h>
4
5 struct line {
6   struct line *next;
7   char x[1];
8 };
9
10 unsigned int
11 r(unsigned int max)
12 {
13   unsigned int r, l;
14
15   l = (RAND_MAX + 1U) - ((RAND_MAX + 1U) % max);
16   do
17     r = random();
18   while (r >= l);
19   return r % max;
20 }
21
22 int
23 main(int argc, char **argv)
24 {
25   char buf[4096];
26   struct line *f = NULL, *n, **b, **w;
27   int cnt = 0, i, j, k;
28
29   while (fgets(buf, sizeof(buf)-1, stdin))
30     {
31       if (!strchr(buf, '\n'))
32         {
33           fprintf(stderr, "Line too long\n");
34           return 1;
35         }
36       n = malloc(sizeof(struct line) + strlen(buf));
37       if (!n)
38         {
39           fprintf(stderr, "Out of memory\n");
40           return 1;
41         }
42       n->next = f;
43       f = n;
44       strcpy(n->x, buf);
45       cnt++;
46     }
47   if (!cnt)
48     return 0;
49   w = b = malloc(sizeof(struct line *) * cnt);
50   if (!b)
51     {
52       fprintf(stderr, "Out of memory\n");
53       return 1;
54     }
55   while (f)
56     {
57       *b++ = f;
58       f = f->next;
59     }
60   srandom(time(NULL));
61   for(i=0; i<cnt; i++)
62     {
63       j = r(cnt);
64       k = r(cnt);
65       n = w[j];
66       w[j] = w[k];
67       w[k] = n;
68     }
69   for(i=0; i<cnt; i++)
70     fputs(w[i]->x, stdout);
71   return 0;
72 }