#!/usr/bin/perl -w

# ----------------------------------------------------------------------
#  Author:      Stuart Robinson
#  Date:        19 September 2003
#  Description: This program takes a list of items from
#               the command-line and provides every 
#               permutation of those items. Given n items, 
#               there will be n! (n factorial) permutations.
#
#  Copyright (C) 2003 Stuart P. Robinson
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
# ----------------------------------------------------------------------

use strict;
use English;

main();

sub main {
    usage() if !defined @ARGV;
    my @permutations = permute(\@ARGV, "");
    for (my $i = 0; $i <= $#permutations; $i++) {
	my $n = $i + 1;
	my $p = $permutations[$i];
	$p =~ s/\#\#\#/ /g;
	print "$n)$p\n";
    }
}

sub permute {
  my $raElements = shift;
  my $context = shift;
  my @permutations;
  my $size = scalar @$raElements - 1;
  for (my $i = 0; $i <= $size; $i++) {
    my $e = $raElements->[$i];
    my $raElementsNew = drop_element($raElements, $i);
    if (scalar @$raElementsNew >= 1) {
      push(@permutations, permute($raElementsNew, "$context###$e"));
    } else {
      push(@permutations, "$context###$e");
    }
  }
  return @permutations;
}

sub drop_element {
  my $rArray = shift;
  my $i = shift;
  my @newArray = @$rArray;
  my ($removed) = splice(@newArray, $i, 1);
  return \@newArray;
}

sub usage {
    print STDERR "$PROGRAM_NAME <ITEM 1> <ITEM 2> ... <ITEM n>\n";
    exit;
}
