http://www.perlmonks.org?node_id=1059865


in reply to combinations of given string

generic solution for arbitrary number of ordered sets to be combined

use v5.10.0; use warnings; use strict; use Data::Dump qw/pp/; my @sets = ( ["A".."C"], [("-") x 3] ); my (@path,@results); sub branch { my $done=1; for my $set ( @sets ){ if (@$set ) { $done=0; push @path, shift @$set; branch(); unshift @$set, pop @path; } } if ($done){ push @results, join "",@path; } } branch(); pp \@results; __END__ [ "ABC---", "AB-C--", "AB--C-", "AB---C", "A-BC--", "A-B-C-", "A-B--C", "A--BC-", "A--B-C", "A---BC", "-ABC--", "-AB-C-", "-AB--C", "-A-BC-", "-A-B-C", "-A--BC", "--ABC-", "--AB-C", "--A-BC", "---ABC", ]

Cheers Rolf

( addicted to the Perl Programming Language)

update

simplified code

update

Formula: be s_1,s_2,...s_n the size of n sets in @sets, the number of combinations is then

fac( sum( s_i) ) ------------------- prod ( fac (s_i) )

or

( Σ si ) ! 
---------- 
  Π (si!)