in reply to Re: All possible number combinations in perl
in thread All possible number combinations in perl

It's not homework, I'm actually trying to build several strings with the combinations that will be used by a seperate input file. Anyway the following code accomplishes what I want (since my largest n will be 5) but this cannot be the best way to do it. I can't use the module option shown below since we are unable to install modules that are no available companywide.
#!/usr/local/bin/perl-5.10.1 -w use strict; my $var = 5; my @list = 1..$var; my @combos; foreach ( 0..($var-1) ){ my @temp_array; push(@temp_array , "$list[$_]"); if($list[$_+1]){push(@temp_array , "$list[$_]$list[$_+1]")} if($list[$_+2]){push(@temp_array , "$list[$_]$list[$_+1]$list[$_+2 +]")} if($list[$_+3]){push(@temp_array , "$list[$_]$list[$_+1]$list[$_+2 +]$list[$_+3]")} if($list[$_+4]){push(@temp_array , "$list[$_]$list[$_+1]$list[$_+2 +]$list[$_+3]$list[$_+4]")} push(@combos, @temp_array); } print "@combos\n";
prints: 1 12 123 1234 12345 2 23 234 2345 3 34 345 4 45 5

Replies are listed 'Best First'.
Re^3: All possible number combinations in perl
by BrowserUk (Patriarch) on Jun 07, 2012 at 21:30 UTC

    That isn't all the combinations:

    [0] Perl> for $k ( 1 .. 5 ) { $i = combinations( [ 1..5 ], $k ); print + @$_ while defined( $_ = $i->next ) };; 1 2 3 4 5 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 4 5 1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5 1 2 3 4 1 2 3 5 1 2 4 5 1 3 4 5 2 3 4 5 1 2 3 4 5

    It may be what you want, but if it is, then you aren't after combinations.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

Re^3: All possible number combinations in perl
by rovf (Priest) on Jun 08, 2012 at 09:27 UTC
    From your example, it doesn't look like you are interested in combinations (otherwise, 235 would be included in your result), but in complete subsequences of a sequence 1..n. Hence, if N equals 100, the subsequence 42 43 44 45 would be in your result set. Right?

    In this case, you just need two nested loops (one for the lower bound of the subsequence, one for the upper bound). There are N*N of such subsequences.
    -- 
    Ronald Fischer <ynnor@mm.st>