shuffle.c revision 1.5 1 /* $NetBSD: shuffle.c,v 1.5 1998/12/04 17:47:06 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.5 1998/12/04 17:47:06 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 __P((void));
48 static void *emalloc __P((size_t));
49 static void *erealloc __P((void *, size_t));
50
51 static size_t *get_shuffle __P((size_t));
52 static void usage __P((void));
53 static void get_lines __P((const char *, char ***, size_t *));
54 static size_t get_number __P((const char *, int));
55
56 int main __P((int, char *[]));
57
58 /*
59 * enomem --
60 * die when out of memory.
61 */
62 static void
63 enomem()
64 {
65 errx(2, "Cannot allocate memory.");
66 }
67
68 /*
69 * emalloc --
70 * malloc, but die on error.
71 */
72 static void *
73 emalloc(len)
74 size_t len;
75 {
76 void *p;
77
78 if ((p = malloc(len)) == NULL)
79 enomem();
80 return p;
81 }
82
83 /*
84 * erealloc --
85 * realloc, but die on error.
86 */
87 void *
88 erealloc(ptr, size)
89 void *ptr;
90 size_t size;
91 {
92 if ((ptr = realloc(ptr, size)) == NULL)
93 enomem();
94 return ptr;
95 }
96
97 /*
98 * get_shuffle --
99 * Construct a random shuffle array of t elements
100 */
101 static size_t *
102 get_shuffle(t)
103 size_t t;
104 {
105 size_t *shuffle;
106 size_t i, j, k, temp;
107
108 shuffle = emalloc(t * sizeof(size_t));
109
110 for (i = 0; i < t; i++)
111 shuffle[i] = i;
112
113 /*
114 * This algorithm taken from Knuth, Seminumerical Algorithms,
115 * page 139.
116 */
117
118 for (j = t - 1; j > 0; j--) {
119 k = random() % (j + 1);
120 temp = shuffle[j];
121 shuffle[j] = shuffle[k];
122 shuffle[k] = temp;
123 }
124
125 return shuffle;
126 }
127
128 /*
129 * usage --
130 * Print a usage message and exit
131 */
132 static void
133 usage()
134 {
135 extern char *__progname;
136 (void) fprintf(stderr,
137 "Usage: %s [-f <filename>] [-n <number>] [-p <number>] [<arg> ...]",
138 __progname);
139 exit(1);
140 }
141
142
143 /*
144 * get_lines --
145 * Return an array of lines read from input
146 */
147 static void
148 get_lines(fname, linesp, nlinesp)
149 const char *fname;
150 char ***linesp;
151 size_t *nlinesp;
152 {
153 FILE *fp;
154 char *line;
155 size_t size, nlines = 0, maxlines = 100;
156 char **lines = emalloc(sizeof(char *) * maxlines);
157
158 if (strcmp(fname, "-") == 0)
159 fp = stdin;
160 else
161 if ((fp = fopen(fname, "r")) == NULL)
162 err(1, "Cannot open `%s'", fname);
163
164 while ((line = fgetln(fp, &size)) != NULL) {
165 if (size > 0 && line[size - 1] == '\n')
166 size--;
167 lines[nlines] = emalloc(size + 1);
168 (void)memcpy(lines[nlines], line, size);
169 lines[nlines++][size] = '\0';
170 if (nlines >= maxlines) {
171 maxlines += 100;
172 lines = erealloc(lines, (sizeof(char *) * maxlines));
173 }
174 }
175 lines[nlines] = NULL;
176
177 *linesp = lines;
178 *nlinesp = nlines;
179 if (strcmp(fname, "-") != 0)
180 (void)fclose(fp);
181 }
182
183 /*
184 * get_number --
185 * Return a number or exit on error
186 */
187 static size_t
188 get_number(str, ch)
189 const char *str;
190 int ch;
191 {
192 char *estr;
193 long number = strtol(str, &estr, 0);
194
195 if ((number == LONG_MIN || number == LONG_MAX) && errno == ERANGE)
196 err(1, "bad -%c argument `%s'", ch, str);
197 if (*estr)
198 errx(1, "non numeric -%c argument `%s'", ch, str);
199 if (number < 0)
200 errx(1, "negative -%c argument `%s'", ch, str);
201 return (size_t) number;
202 }
203
204 int
205 main(argc, argv)
206 int argc;
207 char *argv[];
208 {
209 int i, nflag = 0, pflag = 0, ch;
210 char *fname = NULL;
211 size_t *shuffle;
212 struct timeval tv;
213 char **lines = NULL;
214 size_t nlines = 0, pick = 0;
215
216 while ((ch = getopt(argc, argv, "f:n:p:")) != -1) {
217 switch(ch) {
218 case 'f':
219 fname = optarg;
220 break;
221 case 'n':
222 nlines = get_number(optarg, ch);
223 nflag = 1;
224 break;
225 case 'p':
226 pick = get_number(optarg, ch);
227 pflag = 1;
228 break;
229 case '?':
230 default:
231 usage();
232 }
233 }
234 argc -= optind;
235 argv += optind;
236
237 if ((fname && nflag) || (nflag && (argc > 0)))
238 usage();
239
240 if (fname != NULL)
241 get_lines(fname, &lines, &nlines);
242 else if (nflag == 0) {
243 lines = argv;
244 nlines = argc;
245 }
246
247 gettimeofday(&tv, NULL);
248 srandom(getpid() ^ ~getuid() ^ tv.tv_sec ^ tv.tv_usec);
249 if (nlines > 0)
250 shuffle = get_shuffle(nlines);
251
252 if (pflag) {
253 if (pick > nlines)
254 errx(1, "-p specified more components than exist.");
255 nlines = pick;
256 }
257
258 for (i = 0; i < nlines; i++) {
259 if (nflag)
260 printf("%ld\n", (long)shuffle[i]);
261 else
262 printf("%s\n", lines[shuffle[i]]);
263 }
264
265 return 0;
266 }
267