This program will generate a random permutation of the integers {1, ..., n}.

Feel free to save this source code into a file of your own to try out and/or experiment with.

#!/usr/local/bin/perl -w
#
#    This program will generate a random permutation of the integers
#  { 1, ..., n } for a user specified integer n.  We assume that
#  user inputs a positive integer (if it's negative then we'll get
#  an error as the program executes).
#
#    We use the Markov chain Monte Carlo method for generating the
#  random permuation.
#

use strict;

    my ($n, @nums, $iters, $i, $k, );

      #  seed the random number generator
    srand;  

      #  get input from the user
    print "\nEnter the length of the permutation: ";
    $n = <STDIN>;

      #  initialize with the identity permutation
    @nums = 1 .. $n;  

      #  create the permutation
    $iters = 12 * $n**3 * log($n) + 1;
    for ( $i = 1; $i <= $iters; $i++)
        {
           if (rand(1) <= .5)   #  Flip a coin, and if heads swap
                                # a random adjacent pair of elements.
           {
               $k = int( rand($n-1) );
               ( $nums [$k], $nums [$k + 1] ) = ( $nums [$k + 1], $nums [$k] );
           }
        }

    print "\n@nums \n\n";