From 85e0983e73f32a56093617734ace70c7b3d50fed Mon Sep 17 00:00:00 2001 From: hjp Date: Thu, 10 Feb 2000 00:15:28 +0000 Subject: [PATCH] Added to repository (the code is actually from Oct 1998) --- shuffle/GNUmakefile | 13 ++++++ shuffle/shuffle.c | 107 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 shuffle/GNUmakefile create mode 100644 shuffle/shuffle.c diff --git a/shuffle/GNUmakefile b/shuffle/GNUmakefile new file mode 100644 index 0000000..7762d9e --- /dev/null +++ b/shuffle/GNUmakefile @@ -0,0 +1,13 @@ +include GNUmakevars +include GNUmakerules + +shuffle: shuffle.o + $(CC) $^ -lant -o $@ + +clean: + rm -f *.o shuffle core foo bar + +install: $(BINDIR)/shuffle + +distclean: clean + rm -f *.bak *.d diff --git a/shuffle/shuffle.c b/shuffle/shuffle.c new file mode 100644 index 0000000..969cbb8 --- /dev/null +++ b/shuffle/shuffle.c @@ -0,0 +1,107 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +char *cmnd; + +char **lines; +int nr_lines; +int nr_lines_a; + +unsigned int seed; + +static void usage(void) +{ + fprintf(stderr, "Usage: %s [-s seed]\n", cmnd); + exit(1); +} + +static void readfile(const char *filename) +{ + FILE *fp; + char *ln; + + if (STREQ(filename, "-")) { + fp = stdin; + } else { + fp = efopen(filename, "r"); + } + while ((ln = getline(fp))) { + if (nr_lines >= nr_lines_a) { + nr_lines_a = nr_lines_a * 3 / 2 + 1; + assert (nr_lines_a > nr_lines); + lines = realloc(lines, nr_lines_a * sizeof(*lines)); + assert(lines); + } + lines[nr_lines++] = strdup(ln); + } + if (fp != stdin) { + fclose(fp); + } +} + + +static void shuffle(void) { + int i; + int j; + char *p; + + srand(seed); + for (i = 0; i < nr_lines; i++) { + j = rand() / ((double)RAND_MAX + 1) * nr_lines; + assert (0 <= j && j < nr_lines); + p = lines[i]; + lines[i] = lines[j]; + lines[j] = p; + } +} + + +static void dump(void) { + int i; + + for (i = 0; i < nr_lines; i++) { + puts(lines[i]); + } +} + + +int main(int argc, char **argv) +{ + int c; + int i; + char *p; + + cmnd = argv[0]; + + seed = time(NULL); + while ((c = getopt(argc, argv, "")) != EOF) { + switch (c) { + case 's': + seed = strtoul(optarg, &p, 0); + if (p == optarg || *p != '\0') usage(); + break; + case '?': + usage(); + default: + assert(0); + } + } + + if (optind == argc) { + readfile("-"); + } + for (i = optind; i < argc; i++) { + readfile(argv[i]); + } + shuffle(); + dump(); + return 0; +}