-2

Imagine that I have a string, abc. I want to find all of the combinations/permutations that can be created from the letters in that string.

For example:

abc
bac
acb
cba
...

How can I do this with Perl?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Jody
  • 323
  • 2
  • 11

1 Answers1

5

First, given your example, you are trying to generate permutations rather than combinations: the order of the elements matter for the former, but not for the latter. This means that abc and cba are the same combination, but different permutations.

As to how to do it, I suggest to transform your string into an array (split //, $str will do), then to generate the permutations of this array (see below), and then to join the permutations to get back to strings. As to how to compute the permutations, you can use a few of the cpan modules that exists to do so: have a look at How can I generate all permutations of an array in Perl? for inspiration. For instance, using Algorithm::Combinatorics:

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Algorithm::Combinatorics qw(permutations);

my $string = "abc";

my @perms = map { join "", @$_ } permutations([split //, $string]);

say for @perms;

If performance is a concern, then you should probably use Algorithm::Permute instead: it should be faster. Some answers of the question I linked above show how to use this module.

Dada
  • 6,313
  • 7
  • 24
  • 43