Your solution, and the solutions offered so far, all appear to generate an array with the proposed results. This is okay, but will chew up memory the longer the string of bases. *

What you really want is a lazy iterator that will fetch the next sequence in the solution space. The following does what you want, at a greatly reduced cost in memory

#! /usr/local/bin/perl -w use strict; my @nuc = qw/ A T C G /; sub inc { $_[0] eq 'A' and return 'T'; $_[0] eq 'T' and return 'C'; return 'G'; } sub gen { my @current = @_; my $done = 0; return sub { return if $done; my @res = @current; my $i; ITER: for ($i = 0; $i < scalar @current; ++$i) { if( $current[$i] ne $nuc[-1] ) { $current[$i] = inc($current[$i]); last; } else { $current[$i] = $nuc[0]; } } $done = 1 if $i >= scalar @res; return @res; } } my @set = ('A') x (shift || 3); my $iter = gen( @set ); while( my @iter = $iter->() ) { print "@iter\n"; }

The inc kluge to move to the next base is a bit too ugly, there are better ways of doing this, but I leave that as an exercise to the reader.

If you are interested in learning more about iterators, I draw your attention to Dominus' forthcoming book, Higher Order Perl.


* I thought gaal's for 0 .. n constructed a list. It used to be the case on old perls, but gaal assures me this hasn't been the case in years. Which just goes to show that you learn something every day.

- another intruder with the mooring in the heart of the Perl


In reply to Re: Trying to construct all possible strings from 4 bases [ATCG] (use a closure to generate an iterator) by grinder
in thread Trying to construct all possible strings from 4 bases [ATCG] by monkfan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.