What is wrong with my 2D Array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By xofox

I have looked at lots of forum articles about 2D and 3D arrays and I cannot for the life of me figure out what is wrong with my code here:

    
var mapArray = []    
func _ready():
	randomize()
	mapSize = rand_range(MinimumMapSize,MaximumMapSize)
	for x in range(mapSize):
		mapArray[x].append([])
		for y in range(mapSize):
			mapArray[x][y].append(0)	
:bust_in_silhouette: Reply From: johnygames

You didn’t post enough details (e.g. error messages), but by running your code I concluded that there is an issue with the following lines:

mapArray[x].append([])
mapArray[x][y].append(0)  

You try to add items to invalid indices. Correct your code as follows:

func rnd():
	randomize()
	mapSize = rand_range(0,12)
	for x in range(mapSize):
		mapArray.append([])
		for y in range(mapSize):
			mapArray[x].append(0)
	print(mapArray) 

Now you’ll see that you get a proper 2D array. You were trying to add lists to mapArray[x] which was empty.

If you found this useful, please mark this answer as best, so that others can find it useful too.

Ahh so I was referencing the X too soon. Good to know. So now I’d reference it at mapArray[comment0-Y]?

xofox | 2019-10-04 00:51

You start out with an empty array. For mapSize number of iterations (as indicated by your random_range function) fill said array with arrays. So far you should have:

for x in range(mapSize):
        mapArray.append([])

Now your array should be of shape mapSize,0 (where mapSize is the random number from before) and it should look like this when you print it:

[[],[],[]...[],[],[]]

At this point your array has been filled with empty lists. Now you can iterate through them as follows:

for y in range(mapSize):
            mapArray[x].append(0)

This will fill each list in the array with mapsize number of items.

If you want to fill each list with a different number of elements, then change the last line to:

for y in range(“whatever_number_you_want”):
mapArray.append(0)

Now your array is of shape (mapSize, “whatever_number_you_want”)
With your array set and ready, you can now reference your elements with mapArray[comment1-Y]. For instance:

print(mapArray[2][4])

Sidenote: You could even change rand_range to randi() % mapSize to get an integer value.

johnygames | 2019-10-04 02:10