Eric Toporek
Eric Toporek

Reputation: 121

Storing a Matrix in array

I'm trying to make the bidimensional Matrix as an ADT. So given the interface Matrix<T> talking about like a bidimensional array. So I can achieve implement this Interface using a bidimensional Arrar Object[][] matrix as background. Now, I'm trying to implement the interface with an array Object[] matrix as background (i.e. Storing the matrix within an array). I found in this question how to store a 2D array withn a 1D array, I want to do the same, but without using the 2D array. I'm limited to not use list. So any suggestion?

EDIT: input some code.

/* 
* T is a data type which extends the Operable(self-defined) interface
* We're thinking about a numerical matrix so, other operations are the sum, the product etc etc.
* The idea is to make the operations in terms of the backgorund, which in the two- dimensional is pretty easy. But in a unidimensional array?
*/

//Bidimensional background

public class ArrayedMatrix<T extends Operable> implements Matrix<T> {

private Object[][] matrix;


public ArrayedMatrix(int rows, int cols) {
    matriz = new Object[rows][cols];
}


public ArrayedMatrix(T[][] matriz) {
    this.matrix = matriz;
}

//Unidimensional Background
public class LinearMatrix<T extends Operable> implements Matrix<T> {

Object[] matrix;
int rows,cols;

public LinearMatrix(int n, int m) {
    matriz = new Object[n*m];
    rows = n;
    cols = m;

}
//Temporal constructor, this is the one i want to edit
public LinearMatrix(Object[][] mat){
    rows = mat.length;
    cols = mat[0].length;
    matrix = new Object[rows*cols];
    for (int row = 0, count = 0; row < rows ; row++) {
    for (int col = 0; col < cols ; col++) {
        matriz[count] = mat[row][col];
        count++;
    }
}
}

Okay, the matter is, if I define the constructor of the Matrix with the 2D array as parameter, every operation will be less efficent than expected, so I want to make a constructor with another kind of collection as parameter.

Upvotes: 0

Views: 203

Answers (1)

Josh
Josh

Reputation: 500

Any 2d array can be represented as a 1d array by just "unwrapping" the rows and remembering the number of columns (i.e. the width). For example:

int[] grid = new int[width * height];

int get(int row, int column) {
    return grid[row * this.width + column];
}

Upvotes: 1

Related Questions