在阵列中存储矩阵

时间:2019-03-17 01:14:22

标签: java arrays data-structures

我正在尝试将二维矩阵作为ADT。因此,给定接口Matrix<T>就像二维数组一样。因此,我可以使用二维Arrar Object[][] matrix作为背景来实现此接口。现在,我正在尝试以数组Object[] matrix作为背景来实现该接口(即,将矩阵存储在数组中)。我在this question中找到了如何在不使用1D数组的情况下存储2D数组的方法,但我想这样做但不使用2D数组。我仅限于不使用列表。有什么建议吗?

编辑:输入一些代码。

/* 
* 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++;
    }
}
}

好吧,问题是,如果我以2D数组作为参数定义Matrix的构造函数,则每个操作的效率都将比预期的低,因此我想制作一个具有另一种集合作为参数的构造函数。

1 个答案:

答案 0 :(得分:1)

通过仅“展开”行并记住列数(即宽度),任何2d数组都可以表示为1d数组。例如:

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

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