I need to optimize this piece of code I made because this will run in real-time mode.
It's a matrix shifter that pulls downward and will neglect any transparent element.
Code:
void shiftDown(int col)
{
int x = 0; //transparent element
int N = 5; //size
int i,j,k,l;
for ( i = N - 1;i >= 0; --i )
{
if( map[i][col] == x )
{
for( j = i;j >= 0; --j )
{
if ( map[j][col] != x )
{
for ( l = i, k = j;l >= 0; --l, --k )
{
map[l][col] = map[k][col];
}
}
}
}
}
}
Data:
(before)
0 2 3 2 0
0 1 4 0 1
1 2 2 0 3
2 1 0 0 4
4 3 1 1 3
(after)
0 2 0 0 0
0 1 3 0 1
1 2 4 0 3
2 1 2 2 4
4 3 1 1 3
^ ^
Other code
int map[][5] =
{
{0, 2, 3, 2, 0},
{0, 1, 4, 0, 1},
{1, 2, 2, 0, 3},
{2, 1, 0, 0, 4},
{4, 3, 1, 1, 3}
};
void printMap();
void shiftDown(int col);
int main()
{
cout << "before\n";
printMap();
for (int i = 0;i < 5; ++i)
{
shiftDown(i);
}
cout << "after\n";
printMap();
cin.get();
return 0;
}
void printMap()
{
for (int row = 0;row < 5; ++row)
{
for (int col = 0;col < 5; ++col)
{
cout << map[row][col] << '\t';
}
cout << endl << endl << endl << endl;
}
}
Note: Looked at my comment again and I need to correct my error. Its int map[N][N]
again. This will not work for M x N matrix.