Array confusion.
Monkey Forums/Monkey Programming/Array confusion.
| ||
oh god I know its been asked a million times, but for some reason my brain just wont work this morning and this is tripping me up. So basically what I am trying to do is create 2D array, the game has 4 stages, each stage has 12 levels, So I thought yeah that means I need to create an array with 4 arrays of 12, which I think is what iv done, but im not getting the results I expect. [monkeycode] Field stage:int[][] '[stage],[score] (stars can be worked out per score) Method new() Self.stage= [New Int[12],New Int[12],New Int[12],new int[12]] Local c:Int=1 For Local s:Int = 0 to 3 For Local b:int = 0 to 11 Self.stage[s][b] = c c+=1 next Next End Method GetScore:Int(_stage,_wave) Return int( self.stage[_stage][_wave] ) End method [/monkeycode] |
| ||
What results are you getting? I assume that if you were to access stage[0][11] you would expect 12 to return? When creating 2d arrays I do it in the following way... [monkeycode] Local arrayHeight:Int = 4 Local arrayWidth:Int = 12 Local data:Int[][] = New Int[arrayHeight][] Local c:Int = 1 For Local s:Int = 0 Until arrayHeight data[s] = New Int[arrayWidth] For Local b:Int = 0 Until arrayWidth data[s][b] = c c += 1 Next Next [/monkeycode] |
| ||
never mind, the array is fine, it was my displaying of the data within the array that was all messed up. had some odd problems with that as well but not worth posting about. |
| ||
Hi, To simplify 2D array management with a 1D array declaration, i always make two function : array_in(value, i, j) : wich store a value in array[i,j] array_out (i,j) : wich return the array[i,j] value |
| ||
Or you use this function: [monkeycode] Function IntArray2D:Int[][](i:Int, j:Int) Local arr:Int[i][] For Local ind:Int = 0 Until i arr[ind] = New Int[j] End Return arr End [/monkeycode] |
| ||
Or you could use this code by muddy_shoes. It allows initialisation of any 2D array [monkeycode] Class ArrayUtil<T> Function CreateArray:T[][](rows:Int,cols:Int) Local a:T[][] = New T[rows][] For Local i:Int = 0 Until rows a[i] = New T[cols] End Return a End End Function Main() Local iArr:Int[][] = ArrayUtil<Int>.CreateArray(128,64) End [/monkeycode] |