Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 25 Nov 2000 14:38:38 -0800
From:      "Crist J . Clark" <cjclark@reflexnet.net>
To:        Sue Blake <sue@welearn.com.au>
Cc:        freebsd-questions@FreeBSD.ORG
Subject:   Re: unsorting
Message-ID:  <20001125143838.Z12190@149.211.6.64.reflexcom.com>
In-Reply-To: <20001126023150.F377@welearn.com.au>; from sue@welearn.com.au on Sun, Nov 26, 2000 at 02:31:53AM %2B1100
References:  <20001126023150.F377@welearn.com.au>

next in thread | previous in thread | raw e-mail | index | archive | help
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




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