in reply to Generate all possibilities

Jeff and larryk,
Thanks for your suggestions.
Jeff, I had already checked out your suggestions but they didn't cut the mustard. I probably wasn't specific enough in my original question but I need all the possibilities not the permutations (I'm not sure if that is the correct usage of possibilities/permutations . . .). Specifically I also need to generate sequences containing all the same base e.g. AAA, TTT etc.

The Ordered Combinations solution as suggested by larryk does what I need, an awesome little piece of code. Thanks to MeowChow, sachmet and tilly.

Here is the final piece of code for the record:

use strict; #generate all posibilites of a DNA sequence my @Bases = qw(A C G T); my $SequenceMinLenght = 1; my $SequenceMaxLength = 3; my @SequenceLenghts = ($SequenceMinLenght...$SequenceMaxLength); #print "@SequenceLenghts\n"; my $SequenceListLength = $#SequenceLenghts; $SequenceListLength ++; print "Number of Sequence lenghts to permute is $SequenceListLength\n" +; my @allSequence = (); my $sequence; my $currLenght; my @Ordered_Combinations_input = (); foreach $currLenght (@SequenceLenghts){ @Ordered_Combinations_input = (); @Ordered_Combinations_input = ($currLenght, @Bases); @allSequence = (@allSequence, (&Ordered_Combinations (@Ordered_Com +binations_input))); } #Prints sequences to screen # - Too many entries after lenght of sequence is grater than 4. my $i=0; foreach my $finalsequence (@allSequence){ $i ++; if ($i == 4){ print "$finalsequence\n"; $i= 0; } else{ print "$finalsequence\t"; } } #Completely blow the GOLF chalange by using a sub name almost as long +as the sub #See http://www.perlmonks.com/index.pl?node_id=75261 for details sub Ordered_Combinations {my$n=shift;--$n?map{my$d=$_;map$d.$_,Ordered +_Combinations($n,@_)}@_:@_};

Replies are listed 'Best First'.
Re: Re: Generate all possibilities
by CharlesClarkson (Curate) on Jun 21, 2001 at 12:05 UTC

    Unless you need some of those variables later, we could eliminate some clutter.

    use strict; use warnings; #generate all posibilites of a DNA sequence my @Bases = qw(A C G T); my $SequenceMinLength = 1; my $SequenceMaxLength = 3; print 'Number of Sequence lengths to permute is ', $SequenceMaxLength - $SequenceMinLength + 1, "\n"; my @allSequence; foreach my $currLength ($SequenceMinLength .. $SequenceMaxLength){ push @allSequence, Ordered_Combinations($currLength, @Bases); } #Prints sequences to screen # - Too many entries after length of sequence is greater than 4. my $i; foreach my $finalsequence (@allSequence){ ++$i % @Bases ? print "$finalsequence\t" : print "$finalsequence\n +"; }

    By using @Bases instead of 4, we get @Base columns, aiding readability.

    sub Ordered_Combinations { my $n = shift; --$n ? map { my $d = $_; map "$d$_", Ordered_Combinations($n,@_) } @_ : @_ }
    HTH,
    Charles K. Clarkson