Please help me come up with a function that turns an array[4][4] 90° counterclockwise.
8 replies, posted
[b]This problem has been fixed, answer bellow[/b]
Please help me with this it's so mind bending for me, i have been trying to do this for several hours now, drawing, planing and can't come up with the right algorithm.
I need to turn this massive/array that is NxN 90° counter clockwise.
The rules are:
I am allowed to use only [u]1[/u] massive/array, mas[4][4] in this case, it's always a perfect square etc. NxN
I'm trying to turn it 90° counter clockwise.
So far I have came up with this.
[code]for(x=0; x<n; x++) {
for(y=0; y<n; y++) {
temp=mas[x][y];
mas[x][y]=mas[y][n-x];
mas[y][n-x]=temp;
}
}[/code]
But it doesn't work right, from this
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
i get this
13 9 5 16
3 10 11 15
2 6 7 14
1 12 8 4
while i need this
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
[b]Edit:[/b]
Here is the working code
And here is the answer, finaly
[code] for (x=0; x<(n+1)/2; x++){
for (y=x; y<n-x; y++){
temp=mas[x][y];
mas[x][y]=mas[y][n-x];
mas[y][n-x]=mas[n-x][n-y];
mas[n-x][n-y]=mas[n-y][x];
mas[n-y][x]=temp;
}
}[/code]
Assuming that you fixed n before "n=n-1" since arrays start from 0, and if you want 4x4 then it will be 0..3;0..3
I would just make a new array and use simple logic to write all 16 required assignments needed.
[QUOTE=sim642;28187043]I would just make a new array and use simple logic to write all 16 required assignments needed.[/QUOTE]
He's only allowed one array
Can't you use 4 temp bytes and write the 4 co-ords that rotate onto each other (eg. the corners) then re-write that back in rotated and repeat that by the number of numbers in one quadrant?
You need 3 swaps to do the corners.
First:
1 2 3 [b]4[/b]
5 6 7 8
9 10 11 12
13 14 15 [b]16[/b]
Second:
1 2 3 16
5 6 7 8
9 10 11 12
[b]13[/b] 14 15 [b]4[/b]
Third:
[b]1[/b] 2 3 16
5 6 7 8
9 10 11 12
[b]4[/b] 14 15 13
Just use the same logic for centers, 1st edges and 2nd edges.
[editline]21st February 2011[/editline]
And you could possibly automate the process.
The size is n apparently. Not necessarily 4x4.
This is actually an interesting problem, although my brain no function properly due to illness, but I can probably figure something out :pseudo:
And here is the answer, finaly
[code] for (x=0; x<(n+1)/2; x++){
for (y=x; y<n-x; y++){
temp=mas[x][y];
mas[x][y]=mas[y][n-x];
mas[y][n-x]=mas[n-x][n-y];
mas[n-x][n-y]=mas[n-y][x];
mas[n-y][x]=temp;
}
}[/code]
Assuming that you fixed n before "n=n-1" since arrays start from 0, and if you want 4x4 then it will be 0..3;0..3
Thanks for the help anyway, this is a nice helpful community.
[QUOTE=Ins1d3r;28187943]And here is the answer, finaly[/QUOTE]
Does that work only for 4x4 or NxN? I got my prototype in Lua finished and it works with everything I've tested.
[url]http://codepad.org/EWV7Hxpd[/url]
table.spin is the important part, rest is just for testing.
Sorry, you need to Log In to post a reply to this thread.