我有以下二维矩阵:
int[][] states=new int[][]{{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
我想用这个输出得到一个 3d 矩阵:
[0,1] | [0,2] | [1,0] | [1,1] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,2] | [1,0] | [1,1] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [1,0] | [1,1] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,1] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,1] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,1] | [1,2] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,1] | [1,2] | [2,0] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,1] | [1,2] | [2,0] | [2,1]
我尝试了以下代码:
int[][] states=new int[][]{{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
int[][][] actions = new int[states.length][states.length][2];
// Remplissage :
for (int i = 0; i < states.length; i++) {
int k = 0;
for (int j = 0; j < states.length; j++) {
for (int c = 0; c < states[i].length; c++) {
actions[i][j] = states[j];
System.out.print(actions[i][j][c] + "\t");
}
}
System.out.println();
}
但我没有得到想要的结果。
答案 0 :(得分:1)
这是我的一次测试运行的结果。
[0,1] | [0,2] | [1,0] | [1,1] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,2] | [1,0] | [1,1] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [1,0] | [1,1] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,1] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,2] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,1] | [2,0] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,1] | [1,2] | [2,1] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,1] | [1,2] | [2,0] | [2,2]
[0,0] | [0,1] | [0,2] | [1,0] | [1,1] | [1,2] | [2,0] | [2,1]
我把问题分解成几块。首先,我创建了三维矩阵。您需要一个嵌套的 for 循环,依次跳过每个元素。
然后我把三维矩阵的结果打印出来了。我从一对开始。我写了一个方法来产生 [0,0]
。然后,我编写了一种方法来生成一行输出。最后,我写了一个方法来生成整个矩阵。
这是完整的可运行示例。
public class CreateMatrix {
public static void main(String[] args) {
CreateMatrix cm = new CreateMatrix();
int[][] states = new int[][] { { 0, 0 }, { 0, 1 }, { 0, 2 },
{ 1, 0 }, { 1, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 }, { 2, 2 } };
int[][][] actions = cm.createActions(states);
System.out.println(cm.createTable(actions));
}
public int[][][] createActions(int[][] states) {
int[][][] actions = new int[states.length][states.length - 1][2];
for (int i = 0; i < states.length; i++) {
int k = 0;
for (int j = 0; j < states.length; j++) {
if (i != j) {
actions[i][k][0] = states[j][0];
actions[i][k][1] = states[j][1];
k++;
}
}
}
return actions;
}
public String createTable(int[][][] actions) {
String output = "";
for (int i = 0; i < actions.length; i++) {
output += createLine(actions[i]);
output += System.lineSeparator();
}
return output;
}
private String createLine(int[][] line) {
String output = "";
for (int i = 0; i < line.length; i++) {
output += createPair(line[i]);
if (i < (line.length - 1)) {
output += " | ";
}
}
return output;
}
private String createPair(int[] pair) {
return "[" + pair[0] + "," + pair[1] + "]";
}
}