Results 1 to 2 of 2

Thread: matrix problem

  1. #1

    Thread Starter
    New Member
    Join Date
    Mar 2001
    Location
    singapore
    Posts
    4
    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.

  2. #2
    Frenzied Member HarryW's Avatar
    Join Date
    Jan 2000
    Location
    Heiho no michi
    Posts
    1,827
    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:

    Code:
    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.
    Harry.

    "From one thing, know ten thousand things."

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width