java - 用一维数组java填充二维数组
问题描述
我有一个矩阵和一个数组,我想从数组值中填充矩阵。
float [][] mat = new float [m][n];
float [] array= new float [3];
例如 :
arr = {1, 2, 3}
尺寸为 4*4 的垫子
垫=
{1, 2, 3, 1
2, 3, 1, 2
3, 1, 2, 3
1, 2, 3, 1}
填充矩阵的方法是什么?
解决方案
根据您的示例,您希望使用数组中的值在矩阵中插入一行。
首先,让我们构建矩阵和数组值:
int m = 3;
int n = 5;
float[][] mat = new float[m][n];
float[] array = {1,2,3,4};
然后,迭代矩阵以准备更新:
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
// update here
}
}
所以,你想要的是使用数组来设置值,当你到达终点时,你重新开始。我看到了两种解决方案:
使用索引
我们增加它,但是当我们达到数组的长度时,使用模返回“0”。
int currentIndex = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
mat[i][j] = array[currentIndex];
currentIndex = (currentIndex + 1 ) % array.length;
}
}
使用矩阵坐标
或者您可以通过对矩阵的两个索引求和然后再次使用模数来获得索引,这允许在没有循环的情况下更新任何值,(如果需要)
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
mat[i][j] = array[(i+j)%array.length];
}
}
此解决方案的一个问题是,您将无法获得矩阵的正确输出,m + n > Integer.MAX_VALUE
因为总和将给出负值,从而给出不正确的索引。
输出
您可以使用以下命令查看结果:
System.out.println(java.util.Arrays.deepToString(mat));
两种解决方案都给出:
[
[1.0, 2.0, 3.0, 4.0, 1.0],
[2.0, 3.0, 4.0, 1.0, 2.0],
[3.0, 4.0, 1.0, 2.0, 3.0]
]
推荐阅读
- reactjs - React Ant 设计表 - 自定义搜索过滤器
- android - 如何在android中创建自定义全屏ovarlay对话框
- c++ - 在 C/C++ 中,我试图在没有 if-else 阶梯的 for 循环中调用不同的函数(在描述中解释)
- css - 如何在中间显示图标和文本
- css - CSS 网格忽略第二列 minmax() 中指定的最小宽度
- r - 我们如何在 shinyapp 中复制具有不同属性名称的现有属性值?
- windows - 在 Inno Setup 中将图标图像添加到上下文菜单
- angular - 将选择器名称转换为可迭代的字符串或对象
- c# - 功能
延长条件 - excel - 有没有可能添加新行并插入更新的公式的方法?