gpt4 book ai didi

java - 将矩阵存储在数组中

转载 作者:行者123 更新时间:2023-11-30 05:43:46 24 4
gpt4 key购买 nike

我正在尝试将二维矩阵制作为 ADT。所以给定接口(interface)Matrix<T>就像二维数组一样谈论。所以我可以使用二维 Arrar Object[][] matrix 来实现这个接口(interface)作为背景。现在,我正在尝试使用数组 Object[] matrix 来实现接口(interface)作为背景(即将矩阵存储在数组中)。我在 this question 中找到如何使用一维数组存储二维数组,我想做同样的事情,但不使用二维数组。我被限制不使用列表。那么有什么建议吗?

编辑:输入一些代码。

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

好吧,问题是,如果我以二维数组为参数定义 Matrix 的构造函数,那么每个操作的效率都会低于预期,所以我想创建一个以另一种集合作为参数的构造函数。

最佳答案

只需“展开”行并记住列数(即宽度),任何二维数组都可以表示为一维数组。例如:

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

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

关于java - 将矩阵存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55203025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com