Help with Multidimensional Arrays
Monkey Forums/Monkey Programming/Help with Multidimensional Arrays
| ||
I see in the documentation that there you can do an array of an array of Ints. But there is no indication of how to manipulate the elements within such an array. Does anyone have any sample code they could share on how to simulate a multidimentional array in monkey? |
| ||
For a simple :Int[2][2] array, an array of arrays can be declared like this:'Import mojo Global myarray:=[New Int[2],New Int[2]] Function Main() myarray[0][0]=20 myarray[0][1]=30 Print myarray[0][1] End |
| ||
.. |
| ||
Thanks guys. This helped alot. |
| ||
SA, cool. |
| ||
Could we not have some syntactic sugar to enable us to declare these as if they were multi-dimensional? |
| ||
I try to create multidimentional field array like this but fail. Please helpField blurpos:Int[5][2] |
| ||
I've made these, they are incredibly basic, but better than nothing:Class Array2D<T> Field arr:T[] Field i:Int Field length1:Int, length2:int Method New(a:Int, b:Int) arr = New T[a*b] length1 = a length2 = b i = b End Method New(a:Int, b:Int, t:T) arr = New T[a*b] length1 = a length2 = b i = b For Local k:Int = 0 Until a*b arr[k] = t next End Method get:T(x:Int, y:Int) Return arr[x*i + y] End Method set:void(x:Int, y:Int, t:T) arr[x*i + y] = t End End Class Array3D<T> Field arr:T[] Field j:Int, i:Int Field length1:Int, length2:Int, length3:int Method New(a:Int, b:Int, c:int) arr = New T[a*b*c] length1 = a length2 = b length3 = c i = b*c j = c End Method New(a:Int, b:Int, c:Int, t:T) arr = New T[a*b*c] length1 = a length2 = b length3 = c i = b*c j = c For Local k:Int = 0 Until a*b*c arr[k] = t next End Method get:T(x:Int, y:Int, z:int) Return arr[x*i + y*j + z] End Method set:void(x:Int, y:Int, z:Int, t:T) arr[x*i + y*j + z] = t end End |
| ||
Here's what I use (the Generic class has various generic functions, including these):' Usage example: Local a:Int[][] = Generic< Int >.AllocateArray( 3, 5 ) a[ 2 ][ 4 ] = 4 Print a[ 2 ][ 4 ] ' Class for generic functions Class Generic< T > ' Allocate a 1D array of objects Function AllocateArray:T[]( i:Int ) Local arr:T[] = New T[ i ] Return arr End ' Allocate a 2D array of objects Function AllocateArray:T[][]( i:Int, j:Int ) Local arr:T[][] = New T[ i ][] For Local index:Int = 0 Until i arr[ index ] = AllocateArray( j ) Next Return arr End End Or you can just do it manually. Look in bananas/gerryq/picpuzzle for an example of a 3D array of ints allocated the 'normal' way. |