我正在尝试使用具有不同列数的wach行转置矩阵。 例如,我正在尝试的是这个
public Object[][] transpose (Object[][] data) {
Object temp = new Object[data[0].length][];
for (int i = 0; i < data.length; i++) {
temp[i] = new Object[data[i].length];
for ( int j = 0; j < data[i].length; j++) {
temp[j][i] = data[i][j]
}
}
return temp;
}
看来第四行不能正常工作,我不太清楚如何解决它。
答案 0 :(得分:1)
如果您的输入如下:
[ 7, 4, 1]
转置结果可能是其中之一:
[ [ 1, 2 ],
[ 3, 4, 5, 6 ],
[ 7 ] ]
在任何一种情况下,结果都应该包含与最长行一样多的列,而不是第一行。
SIMPLE COMPACT
[ [ 1, 3, 7 ], [ [ 1, 3, 7 ],
[ 2, 4, null ], [ 2, 4 ],
[ null, 5, null ], [ null, 5 ],
[ null, 6, null ] ] [ null, 6 ] ]
public static Object[][] transposeSimple(Object[][] data) {
int maxLen = 0;
for (Object[] row : data)
if (row.length > maxLen)
maxLen = row.length;
Object[][] temp = new Object[maxLen][data.length];
for (int i = 0; i < data.length; i++)
for (int j = 0; j < data[i].length; j++)
temp[j][i] = data[i][j];
return temp;
}
<强>测试强>
public static Object[][] transposeCompact(Object[][] data) {
int maxLen = 0;
for (Object[] row : data)
if (row.length > maxLen)
maxLen = row.length;
Object[][] temp = new Object[maxLen][];
for (int i = 0; i < temp.length; i++) {
for (maxLen = data.length; maxLen > 0; maxLen--)
if (data[maxLen - 1].length > i)
break;
temp[i] = new Object[maxLen];
for (int j = 0; j < maxLen; j++)
if (i < data[j].length)
temp[i][j] = data[j][i];
}
return temp;
}
<强>输出强>
System.out.println(Arrays.deepToString(transposeSimple(new Object[][] {
{ 1, 2 },
{ 3, 4, 5, 6 },
{ 7 },
})));
System.out.println(Arrays.deepToString(transposeCompact(new Object[][] {
{ 1, 2 },
{ 3, 4, 5, 6 },
{ 7 },
})));