Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would implement this as a ragged array, with A[n][0] always returning the element on the diagonal. A[n][1] will return the item just to the right of the diagonal, A[n][2] will return the item to the left of the diagonal, and so. Then, you just need a function that maps matrix index [i,j] to ragged array index[r][s].</p> <p>This has the advantage of sparsity, and if your values stay close to the diagonal the arrays are not very long.</p> <hr> <p>Alternatively, you could have this definition:</p> <pre><code>struct Row { int InitialOffset; int NumElements; int[] Values; } </code></pre> <p>Then you would have a Row[]. Retrieving a value based on matrix index would look like this:</p> <pre><code>//matrix is merely an array of rows... int GetValue(*matrix this, int i, int j) { Row CurrentRow = (*this)[i]; if (CurrentRow.InitialOffset &gt; j) return 0; else if (CurrentRow.InitialOffset + CurrentRow.NumElements &lt; j) return 0; return CurrentRow.Values[j - CurrentRow.InitialOffset] } </code></pre> <p>My C syntax is a little hazy, but you should get the idea.</p> <hr> <p>Based on your demonstration, I would recommend this:</p> <pre><code>struct Matrix { int[,] Data int[] StartOffset; int[] NumberElements; } </code></pre> <p>Used as follows...</p> <pre><code>int GetValue(*Matrix this, int i, int j) { if (this.StartOffset[i] &gt; j) return 0; else if (this.StartOffset[i] + this.NumberElements[i] &lt; j) return 0; return this.Data[i, j-this.StartOffset[i]]; } </code></pre> <p>Your initialization procedure would look something like this</p> <pre><code>//Data is a struct that holds row index, col index, and value Matrix* InitMatrix (*Data values, int numVals) { //loop through values to find longest row and number of rows //create new matrix, malloc matrix for longrow * numRows //malloc numrows elements for StartOffset and NumItems //foreach row, find min() and max()-min() of col indexs and //store in StartOffset and NumItems } </code></pre> <p>You need to do some processing, but data compression isn't cheap.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload