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

二维数组打乱元素

代码:

//二维数组打乱元素:
package java02;
import java.util.Random;
public class Shuffle2DArrayElements {public static void main(String[] args) {//用静态初始化法定义一个二维数组:int[][] arr1 = new int[][]{{1,2,3},{4,5,6,7},{8,9}};//将二维数组转变为一维数组:int index1 = 0;int[] arr2 = new int[9];for(int i = 0; i < arr1.length; i++) {for(int j = 0; j <arr1[i].length; j++) {arr2[index1] = arr1[i][j];index1++;}}//复制数组:int[] tempArr = copyArr(arr2);//防止打乱后的数组仍然未打乱:boolean result = true;while(result) {//打乱一维数组:Random r = new Random();int count1 = r.nextInt(arr2.length);int count2 = r.nextInt(arr2.length);int temp = arr2[count1];arr2[count1] = arr2[count2];arr2[count2] = temp;result = sameArr(arr2, tempArr);}//将一维数组还原为二维数组:int index2 = 0;for(int i = 0; i < arr1.length; i++) {for(int j = 0; j < arr1[i].length; j++) {arr1[i][j] = arr2[index2];index2++;}}//打印二维数组:System.out.println("{");for(int i = 0; i < arr1.length; i++) {System.out.print("{");for(int j = 0; j < arr1[i].length; j++) {System.out.print(arr1[i][j] + " ");}System.out.println("}");}System.out.println("}");}//定义一个方法用于判断新的二维数组是否与原来的二维数组一样:public static boolean sameArr(int[] arr2, int[] tempArr){for(int i = 0; i < arr2.length; i++) {if(arr2[i] != tempArr[i]) {return false;}}return true;}//定义一个方法用于数组复制:public static int[] copyArr(int[] arr2) {int[] copyArray = new int[arr2.length];for(int i = 0; i < arr2.length; i++) {copyArray[i] = arr2[i];}return copyArray;}
}

运行结果:

http://www.lryc.cn/news/585662.html

相关文章:

  • 【环境配置】KAG - Windows 安装部署
  • 开源界迎来重磅核弹!月之暗面开源了自家最新模型 K2
  • 从代码学习深度学习 - 针对序列级和词元级应用微调BERT PyTorch版
  • T16IZ遥控器教程__遥控器与无人机对频
  • spring-boot项目集成spring-ai
  • 基于k8s环境下pulsar高可用测试和扩缩容(下)
  • Web攻防-SSTI服务端模版注入利用分类语言引擎数据渲染项目工具挖掘思路
  • 华为认证笔试考试中心/VUE考场考试规则与环境欣赏
  • 智慧水文站系统:实时监控、全要素监测与AI辅助
  • 爬虫练习1
  • 数据库报错:Column ‘xxx‘ in field list is ambiguous
  • pyQt基础4(对话框)
  • JAX study notes[16]
  • Java项目中图片加载路径问题解析
  • Python Day10
  • LLM场景下的强化学习【GRPO】
  • Spring Boot整合MyBatis+MySQL实战指南(Java 1.8 + 单元测试)
  • 上位机知识篇---端口
  • latex格式中插入eps格式的图像的编译命令
  • 异步复习(线程)
  • 【第四节】ubuntu server安装docker
  • 从0开始学习R语言--Day44--LR检验
  • 文章发布易优CMS(Eyoucms)网站技巧
  • 企业IT管理——医院数据备份与存储制度模板
  • Linux自动化构建工具(一)
  • 多表查询-2-多表查询概述
  • 蔚来测开一面:HashMap从1.7开始到1.8的过程,既然都解决不了并发安全问题,为什么还要进一步解决环形链表的问题?
  • 前端面试专栏-算法篇:23. 图结构与遍历算法
  • USB一线连多屏?Display Link技术深度解析
  • React中Redux基础和路由介绍