home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / perl / 7479 < prev    next >
Encoding:
Text File  |  1992-12-17  |  1.7 KB  |  66 lines

  1. Newsgroups: comp.lang.perl
  2. Path: sparky!uunet!mcsun!sunic!dkuug!iesd.auc.dk!uts!id.dth.dk!ej
  3. From: ej@id.dth.dk (Erik Johansen (EMP))
  4. Subject: Re: In search of good idioms.
  5. Message-ID: <ej.724585686@id.dth.dk>
  6. Sender: news@id.dth.dk (USENET News System)
  7. Organization: Department of Computer Science
  8. References: <BzCw1H.H24@NeoSoft.com>
  9. Date: Thu, 17 Dec 1992 09:48:06 GMT
  10. Lines: 54
  11.  
  12. claird@NeoSoft.com (Cameron Laird) writes:
  13.  
  14. >I'm a newbie perl-plucker.  I'm working through some
  15. >exercises I've set myself, in an effort to develop
  16. >some taste in matters of perl style.  Current problem:
  17. >write a permute program.  Such a program would, for
  18. >example, when presented with input
  19.  
  20. >    permute a1 zebra third
  21.  
  22. >generate output something like
  23.  
  24. >    a1 zebra third
  25. >    a1 third zebra
  26. >    zebra a1 third
  27. >    zebra third a1
  28. >    third a1 zebra
  29. >    third zebra a1
  30.  
  31. Sure, I wrote a piece of code that should do that:
  32.  
  33. ------- Cut here --------
  34. #!/usr/local/bin/perl
  35. print "Permuting (", join(" ", @ARGV), ")\n";
  36.  
  37. # Count first down by one so we don't skip first solution
  38. $index[ $pos = $#ARGV ]--;   # So @index is (0,0,0..., -1)
  39.  
  40. permutation:
  41.  while ( $pos >= 0 )
  42.   {
  43.    $index[$pos--] = 0, next  if ++$index[ $pos ] > $#ARGV;
  44.  
  45.    undef @used;  # Check to see if number occurs twice, then loop
  46.    foreach $idx ( @index )
  47.     { $pos = $#ARGV, next permutation  if $used[ $idx ]++; }
  48.  
  49.    print join(" ", @ARGV[ @index ]), "\n";
  50.    $pos = $#ARGV;
  51.   }
  52. ------- Cut here --------
  53.  
  54. I tried it out and it gives the output you requested.
  55.  
  56.  
  57.   Hope this helps
  58.   Erik Johansen
  59.  
  60. ---
  61.     $txt=" ltrterhnuc--sor eep-\nkJ.a "; srand(53747414);
  62.     for (1..26) { print substr($txt,rand 27,1); }  ### Is this a random write ?
  63.  
  64. Erik Johansen / Institute for Computer Science / Danish Technical University
  65. ej@id.dth.dk
  66.