in reply to Trying to construct all possible strings from 4 bases [ATCG]

this seemes to be a case for recursive programming. if i understood you correctly, this code should do what you want.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $l = 2; #Motif Length my @nucs = qw/A T C G/; my @enum = enum( $l, \@nucs ); print Dumper \@enum; sub enum { return @{$_[1]} unless --$_[0]; map { my $nuc = $_; map { $nuc . $_ } @{$_[1]} } enum( $_[0], $_[1 +]); }

Replies are listed 'Best First'.
Re^2: Trying to construct all possible strings from 4 bases [ATCG]
by monkfan (Curate) on Feb 21, 2005 at 11:24 UTC
    Hi Taumaril,
    Thanks so much for answering me.

    Using recursive along with map is way tooooo.. high for me.
    Would you mind explain it with "for" loop instead?

    As I don't have a strong background algorithmic way of thinking,
    I would like to understand recursion in more basic way.
    I hope this is not too much to ask ;-)

    Regards,
    Edward
      hi,
      it's not too mutch to ask. in fact i'm relay glad to explain some code, 'cause it shows, that you are willing to learn. so here it comes:

      ### my recursive subroutine ########################### sub enum { ### return the list of elements (aka nucleotides) if this is the l +ast ### recursion. ### also note that --$_[0] decrements the counter _before_ it is t +ested ################################################################## +##### return @{$_[1]} unless --$_[0]; ### define a variable which holds my return values ################################################## my @return; ### iterate over the return values of the next recursion ######################################################## for ( enum( $_[0], $_[1] ) ){ my $nuc = $_; ### iterate over all nucleotides ################################ for ( @{$_[1]} ) { push @return, $nuc . $_; } } ### return the list so far to the prior recursion ################################################# return @return; }

      if you have problems to understand how it works, try to think about what happens, when $_[0] = 1 then think about what happens, when $_[0] = 2 and then you should get it.
      if you don't understand this at all, it could be because my english is not even close to perfect. so maybe i just didn't explain it correct, which means "don't hesitate to ask questions" :-)