gpt4 book ai didi

java - 转置二维数组仅适用于矩形数组 - Java

转载 作者:行者123 更新时间:2023-12-02 01:41:59 25 4
gpt4 key购买 nike

我有一个类,它的方法可以在给定数组、行和列的情况下转置数组

public class Transpose {

public static void main(String[] args) {
int[][] array = new int[6][5];

System.out.println("Original:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] += i+1;
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println();
transpose(array, 6, 5);
}

public static void transpose(int[][] array, int arrayRows, int arrayColumns)
{
int[][] transposedArray = new int[arrayRows][arrayColumns];
System.out.println("Transposed:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
transposedArray[i][j] = array[j][i];
System.out.print(transposedArray[i][j] + " ");
}
System.out.println();
}
}
}

我得到的输出如下所示:

Original:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6

Transposed:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

我意识到该方法仅在 arrayRowsarrayColumns 的值相同时才有效,例如:6、6 5, 5。我尝试将值彼此相反,将行放在列中,反之亦然,但它不起作用。如何使该方法适用于非矩形/方形数组?

最佳答案

请参阅行注释以获取解释。这些是我修改的唯一几行。

public static void transpose(int[][] array, int arrayRows, int arrayColumns) {
int[][] transposedArray = new int[arrayColumns][arrayRows]; //swap number of rows and columns
System.out.println("Transposed:");
for (int i = 0; i < transposedArray.length; i++) { //take the length of transposedArray, not array
for (int j = 0; j < transposedArray[i].length; j++) { //take the length of transposedArray, not array
transposedArray[i][j] = array[j][i];
System.out.print(transposedArray[i][j] + " ");
}
System.out.println();
}
}

关于java - 转置二维数组仅适用于矩形数组 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54338619/

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