Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: dimensioning arrays

by eg (Friar)
on Feb 16, 2001 at 15:35 UTC ( [id://58836]=note: print w/replies, xml ) Need Help??


in reply to dimensioning arrays

You'll want to read perldata, perllol and perldsc (and maybe perlref and perlreftut for good measure :)

What you'll want to do is make a reference to a list of a list (of a list of a list ... etc.) For example:

my $array_1 = [ 1, 2, 3 ]; # 1d my $array_2 = [ [1, 2, 3], [1, 2, 3], [1, 2, 3] ]; #2d my $array_3 = [ [ [1, 2, 3], [1, 2, 3], [1, 2, 3] ], [ [1, 2, 3], [1, 2, 3], [1, 2, 3] ], [ [1, 2, 3], [1, 2, 3], [1, 2, 3] ], ]; # 3d ... etc.

which can be extended to however many dimensions you want. Using an array ref makes things easy because you can just pass $array_1, $array_2, $array_3 around as you would any ol' scalar. A specific cell in your n-dimensional array can be referenced as:

$array_1->[$x]; $array_2->[$x][$y]; $array_3->[$x][$y][$z]; ... etc.

Or, by "fixed dimensions" do you mean that your n-dimensional array is of a pre-determined size? In that case you can always use the old trick of storing everything in a single array with a pre-declared length and calculating every element's position (see your favorite algorithms/data structures book for details.)

update: I forgot to mention, if your n-dimensional array is sparsely populated, you might look into using a hash and "multidimensional array emulation".

my %array = (); $array{$x1,$y1,$z1} = something; $array{$x2,$y2,$z2} = something else; ...

Obviously this is Terribly Bad if you need to loop around your array and, frankly, I've never had much use for this, but I thought I should bring it up in case it happens to work for you ...

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-19 20:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found