Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 20 Apr 1999 20:03:15 GMT
From:      howardjp@wam.umd.edu
To:        FreeBSD-gnats-submit@freebsd.org
Subject:   bin/11248: Shuffle
Message-ID:  <199904202003.UAA88872@byzantine.student.umd.edu>

next in thread | raw e-mail | index | archive | help

>Number:         11248
>Category:       bin
>Synopsis:       Shuffle
>Confidential:   no
>Severity:       non-critical
>Priority:       low
>Responsible:    freebsd-bugs
>State:          open
>Quarter:        
>Keywords:       
>Date-Required:
>Class:          change-request
>Submitter-Id:   current-users
>Arrival-Date:   Tue Apr 20 17:00:01 PDT 1999
>Closed-Date:
>Last-Modified:
>Originator:     James Howard
>Release:        FreeBSD 3.1-STABLE i386
>Organization:
University of Maryland
>Environment:

FreeBSD byzantine.student.umd.edu 3.1-STABLE FreeBSD 3.1-STABLE #9: Tue Apr 13 20:32:14 GMT 1999     root@byzantine.student.umd.edu:/usr/src/sys/compile/BYZANTINE  i386

>Description:

This is shuffle.1 from NetBSD.  Shuffle takes the command line arguments 
and prints them out in random order.  When I first needed this, I just 
added an option to echo(1) but that ended up breaking make world.  So I 
just grabbed this from NetBSD and installed it instead.  It is really nice.

>How-To-Repeat:
>Fix:
	
Below is a shar containing the source to NetBSD's shuffle.  I only needed
to add the line "#include <limits.h>" to make it build correctly.

# 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: Makefile,v 1.1 1998/09/23 21:05:59 perry Exp $
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: shuffle.1,v 1.2 1998/09/24 12:28:39 christos Exp $
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 f Ar filename ...
X.Op Fl n Ar number
X.Op Fl p Ar number
X.Op Ar arg
X.Op Ar ...
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 the
X.Fl f
Xoption is given, the data is taken from that files' contents or if the
Xfilename is
X.Ar -
X.Dq stdin .
X.Pp
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.Pp
XIf the
X.Fl p
Xoption is given, its argument is treated as a number, and the program
Xprints that number of randomly selected lines or arguments in a random order.
X.Sh EXAMPLES
X.Bd -literal -offset indent
X$ shuffle a b c d
Xc
Xb
Xd
Xa
X$ shuffle -p 1 a b c d
Xd
X$ shuffle -n 4 -p 2
X0
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.
END-of-shuffle.1
echo x - shuffle.c
sed 's/^X//' >shuffle.c << 'END-of-shuffle.c'
X/*	$NetBSD: shuffle.c,v 1.7 1999/02/03 16:22:16 is Exp $	*/
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 <sys/cdefs.h>
X#ifndef lint
X__RCSID("$NetBSD: shuffle.c,v 1.7 1999/02/03 16:22:16 is Exp $");
X#endif /* not lint */
X
X#include <err.h>
X#include <limits.h>
X#include <stdio.h>
X#include <stdlib.h>
X#include <string.h>
X#include <unistd.h>
X#include <errno.h>
X#include <sys/time.h>
X
Xstatic void enomem __P((void));
Xstatic void *emalloc __P((size_t));
Xstatic void *erealloc __P((void *, size_t));
X
Xstatic size_t *get_shuffle __P((size_t));
Xstatic void usage __P((void));
Xstatic void get_lines __P((const char *, char ***, size_t *));
Xstatic size_t get_number __P((const char *, int));
X
Xint main __P((int, char *[]));
X
X/*
X * enomem --
X *	die when out of memory.
X */
Xstatic void
Xenomem()
X{
X	errx(2, "Cannot allocate memory.");
X}
X
X/*
X * emalloc --
X *	malloc, but die on error.
X */
Xstatic void *
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 * 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
X/*
X * get_shuffle --
X *	Construct a random shuffle array of t elements
X */
Xstatic size_t *
Xget_shuffle(t)
X	size_t t;
X{
X	size_t *shuffle;
X	size_t i, j, k, temp;
X	
X	shuffle = emalloc(t * sizeof(size_t));
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
X	for (j = t - 1; j > 0; j--) {
X		k = random() % (j + 1);
X		temp = shuffle[j];
X		shuffle[j] = shuffle[k];
X		shuffle[k] = temp;
X	}
X
X	return shuffle;
X}
X
X/*
X * usage --
X *	Print a usage message and exit
X */
Xstatic void
Xusage()
X{
X	extern char *__progname;
X	(void) fprintf(stderr,
X    "Usage: %s [-f <filename>] [-n <number>] [-p <number>] [<arg> ...]\n",
X		__progname);
X	exit(1);
X}
X
X
X/*
X * get_lines --
X *	Return an array of lines read from input
X */
Xstatic void
Xget_lines(fname, linesp, nlinesp)
X	const char *fname;
X	char ***linesp;
X	size_t *nlinesp;
X{
X	FILE *fp;
X	char *line;
X	size_t size, nlines = 0, maxlines = 100;
X	char **lines = emalloc(sizeof(char *) * maxlines);
X
X	if (strcmp(fname, "-") == 0)
X		fp = stdin;
X	else
X		if ((fp = fopen(fname, "r")) == NULL)
X			err(1, "Cannot open `%s'", fname);
X
X	while ((line = fgetln(fp, &size)) != NULL) {
X		if (size > 0 && line[size - 1] == '\n')
X			size--;
X		lines[nlines] = emalloc(size + 1);
X		(void)memcpy(lines[nlines], line, size);
X		lines[nlines++][size] = '\0';
X		if (nlines >= maxlines) {
X			maxlines += 100;
X			lines = erealloc(lines, (sizeof(char *) * maxlines));
X		}
X	}
X	lines[nlines] = NULL;
X
X	*linesp = lines;
X	*nlinesp = nlines;
X	if (strcmp(fname, "-") != 0)
X		(void)fclose(fp);
X}
X
X/*
X * get_number --
X *	Return a number or exit on error
X */
Xstatic size_t
Xget_number(str, ch)
X	const char *str;
X	int ch;
X{
X	char *estr;
X	long number = strtol(str, &estr, 0);
X
X	if ((number == LONG_MIN || number == LONG_MAX) && errno == ERANGE)
X		err(1, "bad -%c argument `%s'", ch, str);
X	if (*estr)
X		errx(1, "non numeric -%c argument `%s'", ch, str);
X	if (number < 0)
X		errx(1, "negative -%c argument `%s'", ch, str);
X	return (size_t) number;
X}
X
Xint
Xmain(argc, argv)
X	int argc;
X	char *argv[];
X{
X	int i, nflag = 0, pflag = 0, ch;
X	char *fname = NULL;
X	size_t *shuffle = NULL;
X	struct timeval tv;
X	char **lines = NULL;
X	size_t nlines = 0, pick = 0;
X	
X	while ((ch = getopt(argc, argv, "f:n:p:")) != -1) {
X		switch(ch) {
X		case 'f':
X			fname = optarg;
X			break;
X		case 'n':
X			nlines = get_number(optarg, ch);
X			nflag = 1;
X			break;
X		case 'p':
X			pick = get_number(optarg, ch);
X			pflag = 1;
X			break;
X		case '?':
X		default:
X			usage();
X		}
X	}
X	argc -= optind;
X	argv += optind;
X
X	if ((fname && nflag) || (nflag && (argc > 0)))
X		usage();
X
X	if (fname != NULL)
X		get_lines(fname, &lines, &nlines);
X	else if (nflag == 0) {
X		lines = argv;
X		nlines = argc;
X	}
X
X	gettimeofday(&tv, NULL);
X	srandom(getpid() ^ ~getuid() ^ tv.tv_sec ^ tv.tv_usec);
X	if (nlines > 0)
X		shuffle = get_shuffle(nlines);
X
X	if (pflag) {
X		if (pick > nlines)
X			errx(1, "-p specified more components than exist.");
X		nlines = pick;
X	}
X
X	for (i = 0; i < nlines; i++) {
X		if (nflag)
X			printf("%ld\n", (long)shuffle[i]);
X		else
X			printf("%s\n", lines[shuffle[i]]);
X	}
X
X	return 0;
X}
END-of-shuffle.c
exit






>Release-Note:
>Audit-Trail:
>Unformatted:


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-bugs" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199904202003.UAA88872>