Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a large 2D array and populating it in AS3

I was wondering if there was a better way to create a large 2D array and populate it with a single item with AS3? This is a quick example what I'm currently doing:

private var array:Array = [[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
                           [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
                           [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
                           [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
                           [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]];

But there has to be a more functional way! Thanks in advance.

like image 964
James James Avatar asked Dec 06 '22 04:12

James James


2 Answers

Can't you just use a 'traditional' loop to fill it? Something as simple as

var numCols:uint = 10,
    numRows:uint = 10,
    fillValue:uint = 1,
    array:Array = new Array(),
    i:uint,
    j: uint;

for (i = 0; i < numRows; i++) {
  array.push(new Array());
  for (j = 0; j < numCols; j++) {
    array[i].push(fillValue);
  }
}
like image 180
kkyy Avatar answered Jan 12 '23 13:01

kkyy


I always use a single dimentional array and write my own get/set functions to work out the location in the array for the (x,y) point:

i.e, Getting an element:

return array[x+(y*_width)];

To reset the array or set it (once it's been allocated)

for(var i:uint=0;i<array.length;i++)
    array[i] = 1;

Main points are:

  • You only need to allocate a single array
  • You can reset or set or copy elements really fast
  • I assume flash uses "less" memory or there is less overhead overall as only a single array exists

One down side is making sure you accessor and setter functions do range checking as your results may "work" but not be accurate. (I.e. if x is greater than width but still within the bounds of the array)

I "grew up" on C (the language :-p) so this just always seems the logical way of doing things; Allocate a block of memory and divide it up how you want.

like image 34
Christopher Lightfoot Avatar answered Jan 12 '23 13:01

Christopher Lightfoot