当前位置: 首页 > news >正文

打乱一维数组中的元素,并按照4个一组的方式添加到二维数组中

一维数组:int[] tempArr={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

首先我们先遍历数组

遍历之后,可以把打乱的值在赋值给数组中

public class a {
    public static void main(String[] args) {
        int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        Random random = new Random();
        for (int i = 0; i < temp.length; i++) {
       int index= random.nextInt(temp.length);
        int t=temp[i];
        temp[i]=temp[index];
        temp[index]=t;
        }


    }
}

遍历一维数组temp得到每一个元素,

把每一个元素依次添加到二维数组当中

这里的 i/4 会随着 i 的递增,以每 4 个元素为一组,逐行填充到二维数组中;而 i%4 则用于确定当前元素在该行的列索引,实现了逐行逐列的填充。

int[][] data=new int[4][4];
        for (int i = 0; i < temp.length; i++) {
            data[i/4][i%4]=temp[i];
        }

遍历二维数组

 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( );
        }

这样就完成了打乱并添加到二维数组中

import java.util.Random;

public class a {
    public static void main(String[] args) {
        int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        Random random = new Random();
        for (int i = 0; i < temp.length; i++) {
       int index= random.nextInt(temp.length);
        int t=temp[i];
        temp[i]=temp[index];
        temp[index]=t;
        }
        //遍历一维数组temp得到每一个元素,
        // 把每一个元素依次添加到二维数组当中
        int[][] data=new int[4][4];
        for (int i = 0; i < temp.length; i++) {
            data[i/4][i%4]=temp[i];
        }

        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( );
        }


    }
}

相关文章:

  • Python基础入门掌握(十五)
  • 删除 Git 历史提交记录中的大文件
  • 大数据学习(71)-三范式构成
  • pycharm-python國際象棋遊戲代碼
  • 【程序人生】成功人生架构图(分层模型)
  • 前端面试:ajax 和 xhr 是什么关系?
  • 内网攻防——红日靶场(一)
  • 织梦dedecms管理员密码重置工具下载
  • 深度学习框架PyTorch——从入门到精通(4)数据转换
  • 深入探讨TK矩阵系统:创新的TikTok运营工具
  • Redis 三主三从集群部署的完整方案
  • 华为营销流程落地方案:MTC=MTL+LTC
  • ETL中的实用功能以及数据集成方式
  • go语言中切片的长度和容量详解
  • opencv测量线距算法以及深入理解轮廓、采样点与 `pointPolygonTest` 及其在测量线距中的应用
  • Qt 中 isHidden 和 isVisible 的区别与使用
  • Spring 导入 XML 配置文件:@ImportResource
  • 力扣Hot100——560. 和为 K 的子数组
  • iwebsec-SQL数字型注入
  • 基于WebRTC的嵌入式音视频通话SDK:EasyRTC跨平台兼容性技术架构实时通信的底层实现
  • 过去24小时中美是否就关税问题进行过接触?外交部:没有
  • 强制性国家标准《危险化学品企业安全生产标准化通用规范》发布
  • 五一去哪儿| 追着花期去旅行,“赏花经济”绽放文旅新活力
  • 宋徽宗《芙蓉锦鸡图》亮相,故宫首展历代动物绘画
  • 体坛联播|安切洛蒂预计执教巴西国家队,利拉德确诊跟腱撕裂
  • 在循环往复的拍摄中,重新发现世界