zoukankan      html  css  js  c++  java
  • Java数组转置

    数组转置,就是将打印的数组的列和行进行位置对换。

    我们就可以用两个for循环遍历数组,然后交换arr[i][j]与arr[j][i]

     1 public class Demo{
     2     public static void main(String[] args){
     3         int[][] arr = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
     4 
     5         for(int i = 0; i < arr.length; i++){
     6             for(int j = 0; j < arr[i].length; j++){
     7                 System.out.print(arr[i][j] + " ");
     8             }
     9             System.out.println();
    10         }
    11         
    12         System.out.println();
    13         System.out.println();
    14 
    15         int temp = 0;
    16 
    17         for(int i = 0; i < arr.length; i++){
    18             for(int j = 0; j < i; j++){
    19                 temp = arr[i][j];
    20                 arr[i][j] = arr[j][i];
    21                 arr[j][i] = temp;
    22             }
    23         }
    24         
    25         for(int i = 0; i < arr.length; i++){
    26             for(int j = 0; j < arr[i].length; j++){
    27                 System.out.print(arr[i][j] + " ");
    28             }
    29             System.out.println();
    30         }
    31         
    32     }
    33 }

    输出结果:

    注意:在进行转置是,只需转置一次,否则转置两次会没有变化

    以上方法只适用于正方形矩阵,下面介绍一种矩形方阵的方法.

     1     public static void main(String[] args){
     2         char[][] chss = new char[][]{
     3             {'a','b','c','d'},
     4             {'e','f','g','h'}
     5         };
     6         char[][] temp = new char[chss[0].length][chss.length];
     7         
     8         for(int i = 0; i < chss.length; i++){
     9             for(int j = 0; j < chss[i].length; j++){
    10                 temp[j][i] = chss[i][j];
    11             }
    12         }
    13 
    14         for(int i = 0; i < temp.length; i++){
    15             for(int j = 0; j < temp[i].length; j++){
    16                 System.out.print(temp[i][j]);
    17             }
    18             System.out.println();
    19         }
    20 
    21     }

    输出结果:

  • 相关阅读:
    fiddler的使用
    redis pipeline
    redis hash map
    redis队列的实现
    PHP-redis中文文档-命令
    websocket
    c++之socket,阻塞模式
    Django上传文件和修改date格式
    通过字符串导入模块
    'CSRFCheck' object has no attribute 'process_request' 报错
  • 原文地址:https://www.cnblogs.com/shenhx666/p/8093504.html
Copyright © 2011-2022 走看看