Home | History | Annotate | Line # | Download | only in shuffle
shuffle.c revision 1.10
      1 /*	$NetBSD: shuffle.c,v 1.10 2001/05/29 23:22:42 perry Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1998
      5  * 	Perry E. Metzger.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgment:
     17  *	This product includes software developed for the NetBSD Project
     18  *	by Perry E. Metzger.
     19  * 4. The name of the author may not be used to endorse or promote products
     20  *    derived from this software without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 #include <sys/cdefs.h>
     35 #ifndef lint
     36 __RCSID("$NetBSD: shuffle.c,v 1.10 2001/05/29 23:22:42 perry Exp $");
     37 #endif /* not lint */
     38 
     39 #include <err.h>
     40 #include <stdio.h>
     41 #include <stdlib.h>
     42 #include <string.h>
     43 #include <unistd.h>
     44 #include <errno.h>
     45 #include <sys/time.h>
     46 
     47 static void enomem(void);
     48 static void *emalloc(size_t);
     49 static void *erealloc(void *, size_t);
     50 
     51 static size_t *get_shuffle(size_t);
     52 static void usage(void);
     53 static void get_lines(const char *, char ***, size_t *);
     54 static size_t get_number(const char *, int);
     55 
     56 int main(int, char *[]);
     57 
     58 /*
     59  * enomem --
     60  *	die when out of memory.
     61  */
     62 static void
     63 enomem(void)
     64 {
     65 	errx(2, "Cannot allocate memory.");
     66 }
     67 
     68 /*
     69  * emalloc --
     70  *	malloc, but die on error.
     71  */
     72 static void *
     73 emalloc(size_t len)
     74 {
     75 	void *p;
     76 
     77 	if ((p = malloc(len)) == NULL)
     78 		enomem();
     79 	return p;
     80 }
     81 
     82 /*
     83  * erealloc --
     84  *	realloc, but die on error.
     85  */
     86 void *
     87 erealloc(void *ptr, size_t size)
     88 {
     89 	if ((ptr = realloc(ptr, size)) == NULL)
     90 		enomem();
     91 	return ptr;
     92 }
     93 
     94 /*
     95  * get_shuffle --
     96  *	Construct a random shuffle array of t elements
     97  */
     98 static size_t *
     99 get_shuffle(size_t t)
    100 {
    101 	size_t *shuffle;
    102 	size_t i, j, k, temp;
    103 
    104 	shuffle = emalloc(t * sizeof(size_t));
    105 
    106 	for (i = 0; i < t; i++)
    107 		shuffle[i] = i;
    108 
    109 	/*
    110 	 * This algorithm taken from Knuth, Seminumerical Algorithms,
    111 	 * page 139.
    112 	 */
    113 
    114 	for (j = t - 1; j > 0; j--) {
    115 		k = random() % (j + 1);
    116 		temp = shuffle[j];
    117 		shuffle[j] = shuffle[k];
    118 		shuffle[k] = temp;
    119 	}
    120 
    121 	return shuffle;
    122 }
    123 
    124 /*
    125  * usage --
    126  *	Print a usage message and exit
    127  */
    128 static void
    129 usage(void)
    130 {
    131 
    132 	(void) fprintf(stderr,
    133     "Usage: %s [-f <filename>] [-n <number>] [-p <number>] [<arg> ...]\n",
    134 		getprogname());
    135 	exit(1);
    136 }
    137 
    138 
    139 /*
    140  * get_lines --
    141  *	Return an array of lines read from input
    142  */
    143 static void
    144 get_lines(const char *fname, char ***linesp, size_t *nlinesp)
    145 {
    146 	FILE *fp;
    147 	char *line;
    148 	size_t size, nlines = 0, maxlines = 128;
    149 	char **lines = emalloc(sizeof(char *) * maxlines);
    150 
    151 	if (strcmp(fname, "-") == 0)
    152 		fp = stdin;
    153 	else
    154 		if ((fp = fopen(fname, "r")) == NULL)
    155 			err(1, "Cannot open `%s'", fname);
    156 
    157 	while ((line = fgetln(fp, &size)) != NULL) {
    158 		if (size > 0 && line[size - 1] == '\n')
    159 			size--;
    160 		lines[nlines] = emalloc(size + 1);
    161 		(void)memcpy(lines[nlines], line, size);
    162 		lines[nlines++][size] = '\0';
    163 		if (nlines >= maxlines) {
    164 			maxlines *= 2;
    165 			lines = erealloc(lines, (sizeof(char *) * maxlines));
    166 		}
    167 	}
    168 	lines[nlines] = NULL;
    169 
    170 	*linesp = lines;
    171 	*nlinesp = nlines;
    172 	if (strcmp(fname, "-") != 0)
    173 		(void)fclose(fp);
    174 }
    175 
    176 /*
    177  * get_number --
    178  *	Return a number or exit on error
    179  */
    180 static size_t
    181 get_number(const char *str, int ch)
    182 {
    183 	char *estr;
    184 	long number = strtol(str, &estr, 0);
    185 
    186 	if ((number == LONG_MIN || number == LONG_MAX) && errno == ERANGE)
    187 		err(1, "bad -%c argument `%s'", ch, str);
    188 	if (*estr)
    189 		errx(1, "non numeric -%c argument `%s'", ch, str);
    190 	if (number < 0)
    191 		errx(1, "negative -%c argument `%s'", ch, str);
    192 	return (size_t) number;
    193 }
    194 
    195 int
    196 main(int argc, char *argv[])
    197 {
    198 	int i, nflag = 0, pflag = 0, ch;
    199 	char *fname = NULL;
    200 	size_t *shuffle = NULL;
    201 	struct timeval tv;
    202 	char **lines = NULL;
    203 	size_t nlines = 0, pick = 0;
    204 
    205 	while ((ch = getopt(argc, argv, "f:n:p:")) != -1) {
    206 		switch(ch) {
    207 		case 'f':
    208 			fname = optarg;
    209 			break;
    210 		case 'n':
    211 			nlines = get_number(optarg, ch);
    212 			nflag = 1;
    213 			break;
    214 		case 'p':
    215 			pick = get_number(optarg, ch);
    216 			pflag = 1;
    217 			break;
    218 		case '?':
    219 		default:
    220 			usage();
    221 		}
    222 	}
    223 	argc -= optind;
    224 	argv += optind;
    225 
    226 	if ((fname && nflag) || (nflag && (argc > 0)))
    227 		usage();
    228 
    229 	if (fname != NULL)
    230 		get_lines(fname, &lines, &nlines);
    231 	else if (nflag == 0) {
    232 		lines = argv;
    233 		nlines = argc;
    234 	}
    235 
    236 	gettimeofday(&tv, NULL);
    237 	srandom(getpid() ^ ~getuid() ^ tv.tv_sec ^ tv.tv_usec);
    238 	if (nlines > 0)
    239 		shuffle = get_shuffle(nlines);
    240 
    241 	if (pflag) {
    242 		if (pick > nlines)
    243 			errx(1, "-p specified more components than exist.");
    244 		nlines = pick;
    245 	}
    246 
    247 	for (i = 0; i < nlines; i++) {
    248 		if (nflag)
    249 			printf("%ld\n", (long)shuffle[i]);
    250 		else
    251 			printf("%s\n", lines[shuffle[i]]);
    252 	}
    253 
    254 	return 0;
    255 }
    256