./combinations.pl a b output: a,a a,b b,a b,b #### #!/usr/bin/perl ################################################################################# #FILE : combinations.pl #USAGE : ./combinations.pl arguments # eg, # ./combinations.pl a b # output: # a,a # a,b # b,a # b,b #DESCRIPTION : This program will give possible combinations or elements # in a set, # eg, # if a,b is the input(argument ot the program # the output is # a,a # a,b # b,a # b,b # the idea to create this program is, when I wanted my program # to work for multiple configurations like a,b etc # then I have to look out for atleast four combinations. #AUTHOR : Targetsmart #CREATED DATE : 17/12/2008 17:12:58 IST # ( NOTE : Date format is DD/MM/YYYY HH:MM:SS ) ################################################################################## use strict; use warnings; use diagnostics; use Data::Dumper; use Clone qw(clone); # for deep copy of data structures our (@Buf,$Possibilities); if(@ARGV){ &process(&populatedata(@ARGV)); }else{ #my @actualdata= qw(connection no-connection); my @actualdata= qw(a b); #my @actualdata= (0..6); &process(&populatedata(@actualdata)); } ################################################################################ # just a replication of actual array into number of arrays of same content # the number of arrays depends on the size of the array # eg, # a,b is actual array # this function will prepare # [a,b], [a,b] # a,b,c is actual array # this function will prepare # [a,b,c], [a,b,c], [a,b,c] sub populatedata { my (@mainResult); push (@mainResult , [@_]) for 0..$#_; return \@mainResult; } ################################################################################ ################################################################################ # this recursive function which is take the replicated array like # [a,b,c], [a,b,c], [a,b,c] # and produce the possible combinations. # like # a,a,a # a,a,b # a,a,c # a,b,a # .... sub process() { my($Data) = shift; my $MyArray = shift @{$Data}; #print Dumper $MyArray; foreach my $Index (@{$MyArray}) { push(@Buf,$Index); # checking the next array if exists if(exists $Data->[0]){ # if there is a next array then supply the data # by doing a clone to retain the actual $data for # recursion, if not cloned then the actual data # reference will not be retained # eg, # consider the array or arrays # [a,b],[a,b] exist # when cloned # a,a # a,b after printing this # recursion will return # but the $Data is already emptied out not available for printing 'b' combination # b,a # b,b # BUT if we clone # a,a # a,b after printing this # recursion will return # but the $Data is will contain [a,b] and available for printing 'b' combination # b,a # b,b &process(clone($Data)); pop(@Buf); }else{ $"=","; # counting the combination sequence number. $Possibilities++; print "$Possibilities,@Buf\n"; pop @Buf; } } } ################################################################################