get all possible permutations of words in string using perl script

793 views Asked by At

I have a string like this , how are you , I want to get all possible shuffle of word like

how are you
are how you
you how are
you are how
are you how
how you are

How can I make it in perl script , i've tried the shuffle function but it returns only one string of shuffle .
If you are not familiar with Perl script, you can tell me the logic only.

Note: The words count in string are not constant.

2

There are 2 answers

0
bgoldst On BEST ANSWER

What you're talking about are permutations. This can be done in Perl with the Algorithm::Permute module:

If you've installed the module, here's a shell one-liner that will do it for you:

perl -e'
 use Algorithm::Permute qw();
 my $str = $ARGV[0]; 
 my @arr = split(/\s+/,$str);
 my $ap = new Algorithm::Permute(\@arr); 
 while (my @res = $ap->next()) { print("@res\n"); }
' 'how are you';
## you are how
## are you how
## are how you
## you how are
## how you are
## how are you
0
serenesat On

You can use List::Permutor CPAN module:

use strict;
use warnings;

use List::Permutor;

my $perm = new List::Permutor qw/ how are you /;
while (my @set = $perm->next)
{
  print "@set\n";
}

Output:

how are you
how you are
are how you
are you how
you how are
you are how

As bgoldst suggested Algorithm::Permute, for faster execution you can write this without using while loop:

use Algorithm::Permute;
my @array = qw(how are you);
Algorithm::Permute::permute {
    print "@array\n";
}@array;