Access the answers to your technology questions today.
Subscribe Now
30-day free trial. Register in 60 seconds.
What Makes Experts Exchange Unique?
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.
Try it out and discover for yourself.
Subscribe Now
30-day free trial. Register in 60 seconds.
Join the Community
Give a Little. Get a Lot.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Join the Community
by: KdoPosted on 2004-01-02 at 09:18:47ID: 10029701
Hi sanko50,
If you have an 8x8 matrix, the elements are already in a predictable order. C organizes a matrix over contiguous memory and converts the matrix syntax [][] into an offset from the first element. Using your 8x8 example, item [0][0] is the first item, item [0][1] is the second, item [1][0] is the eighth, item [2][1] is the 17th, etc.
You can very easily convert that to a one-dimensional array by simply recasting a variable:
int Matrix[8][8];
int *Vector;
Vector = (int *) Matrix;
You can now reference Matrix[0][0] or Vector[0] to get to the same address.
But it appears that the framers of your question have made it tougher than this by organizing the data along diagonals. So let's describe the order of the data in the sample matrix.
0 [0][0]
1 [0][1]
2 [1][0]
3 [2][0]
4 [1][1]
5 [0][2]
6 [0][3]
7 [1][2]
8 [2][1]
9 [3][0]
10 [4][0]
11 [3][1]
12 [2][2]
13 [1][3]
14 [0][4] etc...
You can build a conversion so that looking up item[a][b] returns the currect offset, or you can devise a function to return the offset based on a and b. The length of each diagonal is fixed and predictable. The first diagonal contains the value 0 and has a length of 1. The second diagonal contains the values 1 and 2 and has a length of 2. In fact, the first 8 diagonals increase in length by one item over the previous length. The last 7 diagonal decrease in length from the previous length. The 15 diagonals have lengths of 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1. The diagonals are traversed alternately from lower-left to upper-right, then from upper-right to lower-left. You now have enough information to build your conversion algorithm.
DiagonalLengths[15] = {1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};
int ComputeDiagonalFromItem (int Item) /* Compute the diagonal where a particular item resides */
{
}
int ComputeDiagonalFromMatrix (int x, int y) /* Compute the diagonal of an item based on its x,y coordinates */
{
}
If the diagonal number is even (the first diagonal number is zero) the diagonal is traversed from the lower-left.
Since this does look like a programming assignment, I'll leave the actual coding up to you. Only a small amount of C code is required to actually implement this.
Good Luck,
Kent