Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Populating a vector

by gu (Beadle)
on Dec 15, 2005 at 17:16 UTC ( [id://517034]=perlquestion: print w/replies, xml ) Need Help??

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

Hi monks

Somewhere in a code, I want to populate a (n+1)-vector with one 1 (at the beginning) and then n 0's, like (1, 0, 0, 0).

The first snippet I came with is this ugly unperlish code :
my @poly1_coeffs = () ; push @poly1_coeffs, 1 ; foreach (1..$n) { push @poly1_coeffs, 0 ; }
Then I became a little more enlightened and wrote
my @poly_coeffs = (0) x ($n + 1) ; $poly_coeffs[0]++ ;
Do you see something else/shorter/better ?

Update : I'm dumb.

Thank you, monks.

Gu

Replies are listed 'Best First'.
Re: Populating a vector
by jdporter (Paladin) on Dec 15, 2005 at 17:18 UTC
    @poly1_coeffs = ( 1, (0) x $n );
    We're building the house of the future together.
      /me bangs his head on the first wall he finds.

      Thanks :)

      Gu
Re: Populating a vector
by bageler (Hermit) on Dec 15, 2005 at 17:56 UTC
    You could use a real bitvector instead of a memory hungry array:
    use PDL; $n = 50; $vec = zeroes ($n+1); index($vec,0) .= 1;
      Assuming that his vectors contain only bits...

      thor

      The only easy day was yesterday

        You can put values other than 0 and 1 in PDL vectors and it's still less memory intensive than arrays
Re: Populating a vector
by blazar (Canon) on Dec 15, 2005 at 18:06 UTC
    my @poly_coeffs = (0) x ($n + 1) ; $poly_coeffs[0]++ ;
    Do you see something else/shorter/better ?
    shorter?
    my @poly_coeffs = map !$_+0, 0..$n;
    better? (and even shorter)
    my @poly_coeffs = (1, (0) x $n);
    but I just had to include a map based solution... ;-)

Log In?
Username:
Password:

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

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

    No recent polls found