第八章第十八题(打乱行)(Disorganize)

第八章第十八题(打乱行)(Disorganize)

  • *8.18(打乱行)编写一个方法,使用下面的方法头打乱一个二维int型的行:
    public static void shuffle(int[][] m)
    编写一个测试程序,打乱下面的矩阵:
    int[][] m = {{1,2},{3,4},{5,6},{7,8},{9,10}};
    *8.18(Disorganize)Write a method to scramble a two-dimensional int line with the following method header:
    public static void shuffle(int[][] m)
    Write a test program to disrupt the following matrix:
    int[][] m = {{1,2},{3,4},{5,6},{7,8},{9,10}};

  • 参考代码:

    package chapter08;
    
    public class Code_18 {
        public static void main(String args[]){
            int[][] m = {{1,2},{3,4},{5,6},{7,8},{9,10}};
            shuffle(m);
            for(int i = 0; i < m.length; ++i){
                for(int j = 0; j < m[i].length; ++j){
                    System.out.print(m[i][j] + " ");
                }
                System.out.println();
            }
        }
    
        public static void shuffle(int[][] m){
            int xlen = m.length;
            int ylen = m[0].length;
            for(int i = 0; i < xlen; ++i){
                for(int j = 0; j < ylen; ++j){
                    int n = (int)(Math.random()*ylen);
                    int temp = m[i][n];
                    m[i][n] = m[i][j];
                    m[i][j] = temp;
                }
                int q = (int)(Math.random() * xlen);
                int[] temp1 = m[q];
                m[q] = m[i];
                m[i] = temp1;
            }
        }
    }
    
    
  • 结果显示:

    1 2 
    6 5 
    10 9 
    8 7 
    3 4 
    
    Process finished with exit code 0
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值