Subject: shuffle v2
To: None <tech-userlevel@netbsd.org>
From: Perry E. Metzger <perry@piermont.com>
List: tech-userlevel
Date: 09/22/1998 22:28:22
After some input, I've shuffled shuffle a bit. It now uses stdin as
the source of the things it shuffles (by default), and has a couple
more bells and whistles. Even with the code bloat, it is still tiny. :)

Following discussion with some core folks, I'm going to commit this
soon absent much more discussion.

# This is a shell archive.  Save it in a file, remove anything before
# this line, and then unpack it by entering "sh file".  Note, it may
# create directories; files and directories will be owned by you and
# have default permissions.
#
# This archive contains:
#
#	Makefile
#	shuffle.1
#	shuffle.c
#
echo x - Makefile
sed 's/^X//' >Makefile << 'END-of-Makefile'
X#	$NetBSD$
X
XPROG=	shuffle
X
X.include <bsd.prog.mk>
END-of-Makefile
echo x - shuffle.1
sed 's/^X//' >shuffle.1 << 'END-of-shuffle.1'
X.\"	$NetBSD$
X.\"
X.\" Copyright (c) 1998
X.\" 	Perry E. Metzger.  All rights reserved.
X.\"
X.\" Redistribution and use in source and binary forms, with or without
X.\" modification, are permitted provided that the following conditions
X.\" are met:
X.\" 1. Redistributions of source code must retain the above copyright
X.\"    notice, this list of conditions and the following disclaimer.
X.\" 2. Redistributions in binary form must reproduce the above copyright
X.\"    notice, this list of conditions and the following disclaimer in the
X.\"    documentation and/or other materials provided with the distribution.
X.\" 3. All advertising materials mentioning features or use of this software
X.\"    must display the following acknowledgment:
X.\"	This product includes software developed for the NetBSD Project
X.\"	by Perry E. Metzger.
X.\" 4. The name of the author may not be used to endorse or promote products
X.\"    derived from this software without specific prior written permission.
X.\"
X.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
X.\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
X.\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
X.\" IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
X.\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
X.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
X.\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
X.\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
X.\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
X.\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
X.\"
X.\"
X.Dd September 22, 1998
X.Dt SHUFFLE 1
X.Os
X.Sh NAME
X.Nm shuffle
X.Nd print a random permutation of the command line arguments
X.Sh SYNOPSIS
X.Nm
X.Op Fl c Ar arg ...
X.Op Fl n Ar number
X.Op Ar file
X.Sh DESCRIPTION
XThe
X.Nm
Xprogram prints a random permutation (or
X.Dq shuffle )
Xof its input lines. This can be useful in shell scripts for selecting a
Xrandom order in which to do a set of tasks, view a set of files, etc.
X.Pp
XIf a file name is given as an argument, the file is opened and used as input.
X.Pp
XIf the
X.Fl c
Xoption is given, the rest of the arguments on the command line are
Xshuffled, rather than standard input.
X.Pp
XIf the
X.Fl n
Xoption is given, its argument is treated as a number, and the program
Xprints a random permutation of the numbers greater than or equal to 0
Xand less than the argument.
X.Sh EXAMPLES
X.Bd -literal -offset indent
X$ shuffle -c a b c d
Xc
Xb
Xd
Xa
X$ shuffle -c a b c d
Xd
Xb
Xa
Xc
X$ shuffle -n 4
X0
X2
X1
X3
X.Ed
X.Sh SEE ALSO
X.Xr jot 1
X.Sh HISTORY
XThe
X.Nm
Xprogram first appeared in
X.Nx 1.4 .
X.Sh AUTHORS
XWritten by Perry E. Metzger (perry@piermont.com).
X.Sh BUGS
XThe random number generator isn't that great, and thus the
Xpermutations often aren't that great.
X.Pp
XThe maximum size of an input line is limited to
X.Dv BUFSIZ
Xfrom
X.Pa Aq stdio.h .
XFailures on longer lines are not likely to be pretty.END-of-shuffle.1
echo x - shuffle.c
sed 's/^X//' >shuffle.c << 'END-of-shuffle.c'
X/*	$NetBSD$	*/
X
X/*
X * Copyright (c) 1998
X * 	Perry E. Metzger.  All rights reserved.
X *
X * Redistribution and use in source and binary forms, with or without
X * modification, are permitted provided that the following conditions
X * are met:
X * 1. Redistributions of source code must retain the above copyright
X *    notice, this list of conditions and the following disclaimer.
X * 2. Redistributions in binary form must reproduce the above copyright
X *    notice, this list of conditions and the following disclaimer in the
X *    documentation and/or other materials provided with the distribution.
X * 3. All advertising materials mentioning features or use of this software
X *    must display the following acknowledgment:
X *	This product includes software developed for the NetBSD Project
X *	by Perry E. Metzger.
X * 4. The name of the author may not be used to endorse or promote products
X *    derived from this software without specific prior written permission.
X *
X * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
X * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
X * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
X * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
X * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
X * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
X * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
X * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
X * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
X * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
X */
X
X#include <err.h>
X#include <stdio.h>
X#include <stdlib.h>
X#include <string.h>
X#include <time.h>
X#include <unistd.h>
X
Xchar **global_inputbuf;
Xint global_inputlen;
X
X/*
X * enomem --
X *	die when out of memory.
X */
Xvoid
Xenomem()
X{
X	errx(2, "Cannot allocate memory.");
X}
X
X/*
X * emalloc --
X *	malloc, but die on error.
X */
Xvoid *
Xemalloc(len)
X	size_t len;
X{
X	void *p;
X
X	if ((p = malloc(len)) == NULL)
X		enomem();
X	return(p);
X}
X
X/*
X * ecalloc --
X *	calloc, but die on error.
X */
Xvoid *
Xecalloc(size_t nmemb, size_t size)
X{
X	void *p;
X
X	if ((p = calloc(nmemb, size)) == NULL)
X		enomem();
X	return(p);
X}
X
X
X/*
X * estrdup --
X *	strdup, but die on error.
X */
Xchar *
Xestrdup(const char *str)
X{
X	char *p;
X
X	if ((p = strdup(str)) == NULL)
X		enomem();
X	return(p);
X}
X
X/*
X * erealloc --
X *	realloc, but die on error.
X */
Xvoid *
Xerealloc(ptr, size)
X	void *ptr;
X	size_t size;
X{
X	if ((ptr = realloc(ptr, size)) == NULL)
X		enomem();
X	return(ptr);
X}
X
Xint *get_shuffle(int t)
X{
X	int *shuffle;
X	int i, j, k, temp;
X	
X	shuffle = (int *)ecalloc(t, sizeof(int));
X
X	for (i = 0; i < t; i++)
X		shuffle[i] = i;
X	
X	/*
X	 * This algorithm taken from Knuth, Seminumerical Algorithms,
X	 * page 139.
X	 */
X	for (j = 0; j < t; j++) {
X		k = random()%t;
X		temp = shuffle[j];
X		shuffle[j] = shuffle[k];
X		shuffle[k] = temp;
X	}
X
X	return(shuffle);
X}
X
Xvoid
Xusage(void)
X{
X	errx(1, "usage: shuffle [-c arg ...] [-n number] [file]");
X}
X
Xvoid
Xswallow_input(FILE *input)
X{
X	int insize;
X	int numlines;
X	char **inputbuf, buf[BUFSIZ];
X	
X
X	insize = BUFSIZ;
X	numlines = 0;
X
X	inputbuf = emalloc(sizeof(char *) * insize);
X
X	while (fgets(buf, BUFSIZ, input) != NULL) {
X		inputbuf[numlines] = estrdup(buf);
X		numlines++;
X		if (numlines >= insize) {
X			insize *= 2;
X			inputbuf = erealloc(inputbuf,
X			    (sizeof(char *) * insize));
X		}
X	}
X	inputbuf[numlines] = NULL;
X
X	global_inputbuf = inputbuf;
X	global_inputlen = numlines;
X
X}
X
Xint
Xmain(int argc, char *argv[])
X{
X	extern char *optarg;
X	extern int optind;
X	int nflag, cflag, ch;
X	int *shuffle;
X	int i, t;
X	FILE *input;
X
X	cflag = nflag = 0;
X	while ((ch = getopt(argc, argv, "cn:")) != -1) {
X		switch(ch) {
X		case 'c':
X			cflag = 1;
X			break;
X		case 'n':
X			if ((t = atoi(optarg)) <= 0)
X				errx(1, "%d: number is less than zero\n", t);
X			nflag = 1;
X			break;
X		case '?':
X		default:
X			usage();
X		}
X	}
X	argc -= optind;
X	argv += optind;
X
X	if ((cflag && nflag) || (nflag && (argc > 0)))
X		usage();
X
X	if (cflag)
X		t = argc;
X
X	if (!(cflag || nflag)) {
X
X		if (argc > 1)
X			usage();
X		if (argc == 1) {
X			if ((input = fopen(argv[0], "r")) == NULL)
X				err(1, "could not open %s", argv[0]);
X		}
X		else {
X			input = stdin;
X		}
X		
X		swallow_input(input);
X		t = global_inputlen;
X	}
X
X	srandom(getpid() ^ ~getuid() ^ (int)time(NULL));
X
X	shuffle = get_shuffle(t);
X
X	for (i = 0; i < t; i++) {
X		if (nflag)
X			printf("%d\n", shuffle[i]);
X		else if (cflag)
X			printf("%s\n", argv[shuffle[i]]);
X		else
X			printf("%s", global_inputbuf[shuffle[i]]);
X	}
X}
END-of-shuffle.c
exit