Topic was automatically imported from the old Question2Answer platform.
Asked By
Nimajjj
There is my problem:
I have an array of array and i want to rotate it n time by 90°:
For exemple, go from:
[
[1, 1, 1],
[1, 0, 1],
[0, 0, 1],
[1, 1, 1],
]
To:
[
[1, 0, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1],
]
As a goddot beginner this problem is really too abstract for me, even in python i don’t manage to succeed.
Also sorry for bad english i am a beginner too.
I don’t know if this is the most efficient way to do it, but this should work.
It’s pretty simple. Create a new 2d array, with the opposite dimensions (flip width and height). Then just fill it up with the reversed indices.
Edit: exuin’s answer is better
func rotate_array(arr):
var height = arr.size()
var width = arr.front().size()
var new_arr = []
# Make a 2d array
for i in range(width):
var row = []
row.resize(height)
new_arr.append(row)
# Swap the rows and columns
for i in range(height):
for j in range(width):
new_arr[j][i] = arr[height - i - 1][j]
return new_arr
Nevermind, I just realized this is not what you wanted.
For what you want, I think it might be better to use a dictionary rather than a 2d array. I’ll try to work out an actual solution
# Rotates array 90 degrees clockwise, assuming that array is a full rectangle (all rows same size)
func rotate_array(arr) -> Array:
var new_arr = []
for i in range(len(arr[0])):
var row = []
for j in range(len(arr)):
row.append(arr[len(arr) - j - 1][i])
new_arr.append(row)
return new_arr
To build on your super helpful answer:
func rotate_array(arr,count):
for _c in range(count):
var new_arr = []
for i in range(len(arr[0])):
var row = []
for j in range(len(arr)):
row.append(arr[len(arr) - j - 1][i])
new_arr.append(row)
arr=new_arr
return arr
I’ve added a simple rotate 90° this many times counter.
This gives the benefit of easily rotating or horizontal / vertical flipping [mirroring] any array [like a tilemap for a level].
One could also simulate counter-clockwise rotation for a Tetris-like game.
Currently, I’m using this function for game level generation that is similar to Spelunky.