I'm trying to shift elements in an 2d array in any direction specified. By shift I mean, if left is pressed, each element of the array is moved as far to the left as it can.
so this (0 indicated an empty space),
1 0 2 0
0 3 0 1
1 0 6 9
1 0 0 0
would become
1 2 0 0
3 1 0 0
1 6 9 0
1 0 0 0
This is sudo code of what I have for if 'up' is pressed;
for col = 0 to SIZE
for i = 0 to SIZE - 1
if array[i][col] == 0
for j = i to SIZE
if array[j][col] != 0
array[i][col] = array[row][j]
array[j][col] = 0
break
The actual code is a longer (ie. a check for two identical elements that collide) and I don't want to have 4 copies of this section of code (up, down, left, right), but I can't figure out how to do it any other way.
While it is technically possible to cover all these shifting operations with the same methods, it's probably not as easy to understand (and not as efficient) as creating a dedicated method for each direction.
On the one hand, this is humbling and shattering for a real programmer, but on the other hand ... hey, you can be sure that there will never-ever be more than these four directions.
Or... well, diagonals, maybe? ;-)
What if you made a new array of the same length, and copied the elements into there? Then you would only have to iterate over your array once, making it
O(n)
:There's probably a more elegant solution than this.
Edit: I didn't realize that you were talking about a 2D array until you edited your question. You could adapt this for your needs.