in reply to General Solution: initializing multidimensional arrays

How would you do it?

Recursively.

#! perl -slw use strict; use Data::Dumper::SLC; sub multiDimInit { my( $value, $dim ) = ( shift, shift ); return $value unless $dim; return map{ [ multiDimInit( $value, @_ ) ] } 1 .. $dim; } my @multi = multiDimInit( 12345, 2, 2, 2, 2 ); Dump \@multi, 80, *STDOUT; __END__ P:\test>462436 [ [ [ [ [ '12345', ], [ '12345', ], ], [ [ '12345', ], [ '1234 +5', ], ], ], [ [ [ '12345', ], [ '12345', ], ], [ [ '12345', ], [ '1234 +5', ], ], ], ], [ [ [ [ '12345', ], [ '12345', ], ], [ [ '12345', ], [ '1234 +5', ], ], ], [ [ [ '12345', ], [ '12345', ], ], [ [ '12345', ], [ '1234 +5', ], ], ], ], ]

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.

Replies are listed 'Best First'.
Re^2: General Solution: initializing multidimensional arrays
by Roy Johnson (Monsignor) on Jun 01, 2005 at 14:19 UTC
    Your base case was a level off: your sub guarantees that the bottom level arrays will have one element each. A correction:
    sub multiDimInit { my( $value, $dim ) = ( shift, shift ); return ($value) x $dim unless @_; return map [multiDimInit( $value, @_ )], 1 .. $dim; }

    Caution: Contents may have been coded under pressure.

      Much better++


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
Re^2: General Solution: initializing multidimensional arrays
by dragonchild (Archbishop) on Jun 01, 2005 at 14:02 UTC
    That's so funny - I was going to post the exact same response. :-)

    • In general, if you think something isn't in Perl, try it out, because it usually is. :-)
    • "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"