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... ;-)