PDA

Click to See Complete Forum and Search --> : matrix problem


P81
Mar 11th, 2001, 06:19 AM
here is a matrix problem;

int matrix[10][12] = {
1, 0, 1, 0, 9, 5, 5, 5, 1, 0, 1, 0,
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
1, 9, 9, 9, 1, 0, 1, 0, 5, 5, 5, 0,
0, 1, 0, 1, 0, 1, 9, 9, 9, 1, 0, 1,
1, 5, 5, 5, 1, 0, 1, 0, 1, 0, 1, 0,
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
0, 1, 5, 5, 5, 1, 0, 1, 0, 1, 0, 1,
1, 0, 1, 0, 1, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 0, 1, 0, 9, 5, 5, 5, 9 };

how do i change from the above matrix to the below:?

1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0,
0, 0, 5, 5, 9, 1, 0, 1, 5, 5, 5, 1,
1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0,
0, 9, 0, 1, 1, 1, 9, 9, 0, 1, 0, 1,
1, 1, 9, 9, 0, 0, 1, 0, 9, 1, 0, 0,
0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1,
1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
1, 0, 1, 0, 1, 9, 9, 9, 0, 1, 0, 9,
9, 9, 9, 9, 0, 1, 0, 9, 9, 9, 9, 9 };

where all numbers remains unchanged, except '5' are shifted to the top.

HarryW
Mar 11th, 2001, 08:52 AM
Looks like a simple(ish) sorting problem. You need some sort of loop through each element in each column which will move 5s to the top.

Probably the easiest way to sort, and pretty efficient in this case, is a bubble sort. Try some code like this:


int temp;
int swaps;
for(int x=0; x<12; x++)
{
swaps = 1;
while(swaps == 1)
{
swaps = 0;
for(int y=9; y>0; y--)
{
if(matrix[x][y] == 5 && matrix[x][y-1] != 5)
{
swaps = 1;
temp = matrix[x][y-1];
matrix[x][y-1] = matrix[x][y];
matrix[x][y] = temp;
}
}
};
}


I've probably forgotten something but essentially it's a simple idea. Lop through each column, and each element within each column, swapping the value with the one above if it's a 5. Keep doing that for each row until there any 5s are at the top, then move onto the next column.

The code might not work as it is, but it should be close, I hope.