Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sparseMatrix;
- public class Matrix {
- protected MNode[] pointers;
- protected short rows;
- public Matrix(short columns, short rows) {
- pointers = new MNode[columns];
- this.rows = rows;
- }
- public MNode[] getNodes() {
- return pointers;
- }
- public short getRows() {
- return rows;
- }
- public MNode getNode(short row, short col) {
- MNode root = pointers[col];
- MNode tmp;
- if (row < root.row)
- return null;
- else if (row == root.row)
- return root;
- tmp = root.up;
- while (tmp != root) {
- if (row == tmp.row)
- return tmp;
- if (row < tmp.row)
- return null;
- else if (row == tmp.row)
- return tmp;
- tmp = root.up;
- }
- return null;
- }
- /**
- * Find and delete the element in matrix
- * @param element
- */
- public void delete(MNode element) {
- MNode cur = pointers[element.col];
- while (cur.up != element) {
- cur = element.up;
- }
- if (cur == element) {
- pointers[element.col] = null;
- return;
- }
- cur.up = element.up;
- }
- /**
- * Insert a new MNode into matrix.
- * It's unsafe, lacking checking of boundaries, so safety is up to programmer.
- * @param value
- * @param row
- * @param col
- */
- public void insert(float value, short row, short col) {
- MNode cell = new MNode(value);
- cell.col = col;
- cell.row = row;
- MNode lCell = null;
- MNode rCell = null;
- MNode tmpCell;
- // two way finding closest cell in row
- MNode receiver = null;
- for (int j = 1; j < Math.ceil(pointers.length / 2); j++) {
- if (pointers[j] != null) {
- tmpCell = pointers[j];
- while (tmpCell.up != pointers[j])
- if ((receiver == null) && (tmpCell.row == cell.row))
- receiver = tmpCell;
- }
- if ((col - j > -1) && (null == lCell))
- lCell = receiver;
- else if ((col + j < pointers.length) && (null == rCell))
- rCell = receiver;
- if((null != rCell) && (null != lCell))
- break;
- }
- // looking for closest cells in column
- tmpCell = pointers[col];
- if (tmpCell == null) {
- cell.up = cell;
- return;
- }
- while (tmpCell.up != pointers[col]) {
- if((tmpCell.up.row > row) && (tmpCell.row < row)) {
- cell.up = tmpCell.up;
- tmpCell.up = cell;
- break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment