• JAVA练习题36:打乱一维数组中的数据,并按照4个一组的方式添加到二维数组中


    拼图游戏准备工作

    练习:打乱一维数组中的数据

    1. int[] tempArr = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    2. 要求:打乱一维数组中的数据,并按照4个一组的方式添加到二维数组中。
    package Test;
    
    import java.util.Random;
    
    public class FTest {
        public static void main(String[] args) {
            /*
             * 练习:打乱一维数组中的数据
             * int[] tempArr = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
             * 要求:打乱一维数组中的数据,并按照4个一组的方式添加到二维数组中。
             * */
    
            //1.定义一个一维数组
            int[] tempArr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
            //2.打乱数组中的数据的顺序
            //遍历数组,得到每一个元素,拿着每一个元素跟随机索引上的数据进行交换
            Random r = new Random();
            for (int i = 0; i < tempArr.length; i++) {
                //获取随机索引
                int index = r.nextInt(tempArr.length);
                //拿着遍历到的每一个数据,跟随机索引上的数据进行交换
                int temp = tempArr[i];
                tempArr[i] = tempArr[index];
                tempArr[index] = temp;
            }
            //3.遍历数组
            for (int i = 0; i < tempArr.length; i++) {
                System.out.print(tempArr[i] + " ");
            }
            System.out.println();
            //4.创建一个二维数组
            int[][] data = new int[4][4];
            //5.给二维数组添加数据
            //解法一:
            //遍历一位数组tempArr得到每一个元素,把每一个元素依次添加到二维数组当中
            for (int i = 0; i < tempArr.length; i++) {
                data[i / 4][i % 4] = tempArr[i];
            }
    /*        //解法二:
            //遍历二维数组,给里面的每一个数据赋值
            int index = 0;
            for (int i = 0; i < data.length; i++) {
                for (int j = 0; j < data[i].length; j++) {
                    data[i][j] = tempArr[index];
                    index++;
                }
            }*/
            //遍历二维数组
            for (int i = 0; i < data.length; i++) {
                for (int j = 0; j < data[i].length; j++) {
                    System.out.print(data[i][j] + " ");
                }
                System.out.println();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
  • 相关阅读:
    gitlab版本库安装
    MacOS电脑上面怎么运行Windows软件程序?
    VScode开发STM32/GD32单片机-环境搭建
    KTV如何创新?VR全景打造KTV趣味互动新体验
    Go简单实现协程池
    角逐「视觉感知」万亿市场,这家国内领跑者如何挑战性能天花板?
    整合生成型AI战略:从宏观思维到小步实践
    基于Java+Spring+mybatis+vue+element实现酒店管理系统
    JS中使用递归的一次探索
    我觉得还挺好懂的meta learning 元学习总结
  • 原文地址:https://blog.csdn.net/m0_46457497/article/details/127846334