Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

prepend string to entire array

by mhearse (Chaplain)
on Sep 10, 2003 at 01:31 UTC ( [id://290255]=perlquestion: print w/replies, xml ) Need Help??

mhearse has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to prepend the values of one array on to those fo array1, creatign array2 in the process. Here's what I have, which isn't working.

@array = qw (A B C D E F G); @array1 = qw (1 2 3 4 5 6 7); foreach $x (@array) { foreach $y (@array1) { push (@array2, $x.$y) } }

Replies are listed 'Best First'.
•Re: prepend string to entire array
by merlyn (Sage) on Sep 10, 2003 at 01:34 UTC
      Works, but I need @array2 to contain all possible combinations. Such as:
      A1 B1 C1 D1 E1 F1 G1
      A2 B2 C2 D2 E2 F2 G2
      A3 B3 C3 ..........
        Um, don't you think you should have stated that in your orginal question? :|

        But i do find it amusing that you asked merlyn for code that does combinations. ;)

        UPDATE:
        Limbic~Region pointed me to Re: Character Combinations in which he links to a module tye wrote, Algorithm::Loops. Give it a look.

        jeffa

        I'm in a good mood.

        @array = qw(A B C D E F G); @array1 = qw(1 2 3 4 5 6 7); @array2 = map { my $c=$_;map "$_$c", @array } @array1;

        Hope this helps.

        antirice    
        The first rule of Perl club is - use Perl
        The
        ith rule of Perl club is - follow rule i - 1 for i > 1

Re: prepend string to entire array
by jeffa (Bishop) on Sep 10, 2003 at 01:57 UTC
    I prefer merlyn's solution myself, but for those who get queasy at seeing map, here is another solution:
    my @foo = ('A' .. 'G'); my @bar = (1 .. 7); my @baz; warn "arrays are not the same size!\n" unless @foo == @bar; for my $i (0..$#foo) { push @baz, $foo[$i] . $bar[$i]; }
    Since we need to access more than one array, it is more productive to iterate over the indices, not the elements themselves. ($#foo is the last index of @foo, by the way.)

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: prepend string to entire array
by gmax (Abbot) on Sep 10, 2003 at 09:50 UTC

    A few solutions from a previous thread with a similar problem.

    @result = map scalar reverse, glob("{1,2,3,4,5,6,7}{A,B,C,D,E,F,G}"); # CheeseLord @result=map{$a=$_;map$a.$_,1..7}"A".."G"; # runrig @result=map$_.1..$_.7,"A".."G"; # tilly # which translates, in your case, into @result=map$_.$array1[0]..$_.$array1[$#array1],@array;

    Update: extravagant solutions
    broquaint complained in the CB that I haven't suggested any solutions based on Tree::DAG_Node. While I invite the curious reader to peek at Variant permutation, I propose here a gratuitously heavy DBI solution. :)

    #!/usr/bin/perl -w use strict; use DBI; if (-f "permute") { unlink "permute" or die "can't unlink permute file\n" } my $dbh = DBI->connect("dbi:SQLite:permute", "","",{RaiseError=>1, PrintError=> 0 }) or die "Error in connecton ($DBI::errstr)\n"; my @array = ('A'..'G') ; my @array1 = ( 1 .. 7 ); $dbh->do(qq{CREATE TABLE t1 (a char(1)) }) or die "Error in table creation ($DBI::errstr)\n"; $dbh->do(qq{CREATE TABLE t2 (b char(1)) }) or die "Error in table creation ($DBI::errstr)\n"; $dbh->do("begin"); eval { my $sth = $dbh->prepare (qq{insert into t1 values (?)}); $sth->execute($_) for @array; $sth = $dbh->prepare (qq{insert into t2 values (?)}); $sth->execute($_) for @array1; }; if ($@) { $dbh->do("rollback"); die "error inserting\n"; } else { $dbh->do("commit"); } my $recs = $dbh->selectall_arrayref( qq{select a,b from t1,t2 }) # an infamous CROSS JOIN ! or die "error fetching records\n"; my @results; push @results, join( "", @$_) for @$recs; print "@results\n";
     _  _ _  _  
    (_|| | |(_|><
     _|   
    
Re: prepend string to entire array
by jonadab (Parson) on Sep 10, 2003 at 03:03 UTC

    antirice's nested map is close to what I would have written, but actually what you have works for me...

    ~ raptor1# perl -e ' @array = qw (A B C D E F G); @array1 = qw (1 2 3 4 5 6 7); foreach $x (@array) { foreach $y (@array1) { push (@array2, $x.$y) } } print "@array2\n"; ' A1 A2 A3 A4 A5 A6 A7 B1 B2 B3 B4 B5 B6 B7 C1 C2 C3 C4 C5 C6 C7 D1 D2 D +3 D4 D5 D6 D7 E1 E2 E3 E4 E5 E6 E7 F1 F2 F3 F4 F5 F6 F7 G1 G2 G3 G4 G5 G6 G7 ~ raptor1#

    Maybe you should go into more detail about how this isn't working like you wanted.


    $;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/
Re: prepend string to entire array
by Roger (Parson) on Sep 10, 2003 at 02:33 UTC
    And of course another mundane way of doing this (not as quick or ideomatic as the map solution) is as follows:
    @array = qw (A B C D E F G); @array1 = qw (1 2 3 4 5 6 7); foreach $x (0..$#array1) { foreach $y (0..$#array) { push(@array2, $array[$y].$array1[$x]); } }
Re: prepend string to entire array
by blue_cowdawg (Monsignor) on Sep 10, 2003 at 16:03 UTC

    Try this:

    @array = qw (A B C D E F G); @array2 = map { sprintf("%s%d",$array[$_],$_+1) } (0..$#array);

    Update:Corrected a mistake in my original code after actually shudder testing it.


    Peter L. Berghold -- Unix Professional
    Peter at Berghold dot Net
       Dog trainer, dog agility exhibitor, brewer of fine Belgian style ales. Happiness is a warm, tired, contented dog curled up at your side and a good Belgian ale in your chalice.

      Sorry, but that's wrong.

      Your code will only work if @array1 is (1..7). If it is, say, ('H'..'N'), it will return the wrong result.

            Sorry, but that's wrong. Your code will only work if @array1 is (1..7). If it is, say, ('H'..'N'), it will return the wrong result.
        Two words: Problem Definition
        Based on what you stated as your orginal problem then what I proposed will work. However, given your refinement of your problem set:

        # # Arguments: # $a1 == reference to an array of scalars # $a2 == reference to an array of scalars # Returns: # an array of scalars that are the result of # prepending the contents of $a2 to the elements of $a1 # or undef if the number of elements of $a1 and $a2 # are not the same. sub prepender{ my ($a1,$a2)=@_; my @ax=@$a1; # Dereference only for clarity. my @ay=@$a2; # same as above return undef if $#ax != $#ay; return map { $ay[$_] . $ax[$_] } (0..$#ax); } # # Sample call my @array=('A'..'G'); my @array1=(10..($#array1+9)); my @array2=prepender(\@array,\@array1);
        This includes some basic error checking....


        Peter L. Berghold -- Unix Professional
        Peter at Berghold dot Net
           Dog trainer, dog agility exhibitor, brewer of fine Belgian style ales. Happiness is a warm, tired, contented dog curled up at your side and a good Belgian ale in your chalice.
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://290255]
Approved by Paladin
Front-paged by cchampion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-19 18:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found