From owner-freebsd-questions Sat Nov 25 14:38:43 2000 Delivered-To: freebsd-questions@freebsd.org Received: from mailhost01.reflexnet.net (mailhost01.reflexnet.net [64.6.192.82]) by hub.freebsd.org (Postfix) with ESMTP id 12EF837B4F9 for ; Sat, 25 Nov 2000 14:38:39 -0800 (PST) Received: from 149.211.6.64.reflexcom.com ([64.6.211.149]) by mailhost01.reflexnet.net with Microsoft SMTPSVC(5.5.1877.197.19); Sat, 25 Nov 2000 14:37:09 -0800 Received: (from cjc@localhost) by 149.211.6.64.reflexcom.com (8.11.0/8.11.0) id eAPMcc196273; Sat, 25 Nov 2000 14:38:38 -0800 (PST) (envelope-from cjc) Date: Sat, 25 Nov 2000 14:38:38 -0800 From: "Crist J . Clark" To: Sue Blake Cc: freebsd-questions@FreeBSD.ORG Subject: Re: unsorting Message-ID: <20001125143838.Z12190@149.211.6.64.reflexcom.com> Reply-To: cjclark@alum.mit.edu References: <20001126023150.F377@welearn.com.au> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Mailer: Mutt 1.0i In-Reply-To: <20001126023150.F377@welearn.com.au>; from sue@welearn.com.au on Sun, Nov 26, 2000 at 02:31:53AM +1100 Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk X-Loop: FreeBSD.ORG On Sun, Nov 26, 2000 at 02:31:53AM +1100, Sue Blake wrote: > Is there some fairly simple way I can put a list of letters or words, > or lines of a text file, into a random order? That's called a shuffle, like shuffling a deck of cards. The classic approach is Knuth's algorithm. There's a Perl module to do it if you want to do a quick web search. However, a really quick and ugly approach is to load the list into memory, then just step through it swapping each item with another in a random location. To be a little different, here is an awk(1) script that does it, { line[NR] = $0; } END { for(i=1;i<=NR;i++) { pos = int(rand()*NR); line_hold = line[i]; line[i] = line[pos]; line[pos] = line_hold; } for(i=1;i<=NR;i++) { print line[i]; } } That is not nearly the quickest or most graceful way, but it will work. The incremental improvements to this method are left as an excercise for the reader. ;) -- Crist J. Clark cjclark@alum.mit.edu To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message