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

c#数组内数据打乱

简化版本

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace ConsoleApp1
{internal class Program{static void Main(string[] args){string[] str = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","大王","小王" };string[] str2 = Xipai(str);for (int i = 0; i < str2.Length; i++){Console.WriteLine(str2[i]);}Console.ReadLine();}static string[] Xipai(string[] str1){Random rnd = new Random();for (int i = 0; i < str1.Length; i++){int c = rnd.Next(str1.Length);string temp = str1[i];str1[i] = str1 [c];str1[c]= temp;}return str1;}}
}

优化版本

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApp2
{internal class Program{static void Main(string[] args){Console.WriteLine(Join1(Card()));Console.ReadLine();}static string Join1(string[] arr, string link = ","){string str = "";for (int i = 0; i < arr.Length; i++){str += arr[i];if (i != str.Length - 1){str += link;}}return str;}static string[] Remove(string[] arr, int index){//判断索引是否超出了范围if (index >= arr.Length){return arr;}string[] newArr = new string[arr.Length - 1];//记录新数组元素存储的位置int count = 0;for (int i = 0; i < arr.Length; i++){if (i != index){newArr[count++] = arr[i];}}//返回删除元素后的新数组return newArr;}static string[] Add(string[] arr, string item){string[] newArr = new string[arr.Length + 1];for (int i = 0; i < arr.Length; i++){newArr[i] = arr[i];}newArr[newArr.Length - 1] = item;return newArr;}static string[] Card(){string[] cards = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","大王","小王"};//洗牌之后的扑克牌列表string[] newCards = { };//随机数对象Random random = new Random();while (cards.Length > 0){//随机取扑克牌的索引int index = random.Next(cards.Length);//将随机的扑克牌添加到列表中newCards = Add(newCards, cards[index]);//删除当前取出来的扑克牌cards = Remove(cards, index);}return newCards;}}
}


http://www.mrgr.cn/news/51350.html

相关文章:

  • VS2019 IDE,AddressSanitizer,检测C++代码内存问题
  • 时间序列预测(七)——梯度消失(Vanishing Gradient)与梯度爆炸(Exploding Gradient)
  • 智能电表是如何与远程控制系统连接的?
  • 【Matlab算法MATLAB实现的音频信号时频分析与可视化(附MATLAB完整代码)
  • Net Core发布文件没有View文件夹解决办法!
  • 【黑马redis基础篇】介绍和数据类型
  • WPF基础权限系统
  • Rust : FnOnce与线程池
  • 恺撒密码/置换密码案例
  • UltraISO(软碟通)制作U盘制作Ubuntu20.04启动盘
  • 基于SSM的大学学术交流论坛【附源码】
  • 3.Three.js程序基本框架结构和API说明
  • Unity之XR Interaction Toolkit 射线拖拽3DUI
  • 自适应过滤法—初级
  • KNN算法及KDTree树
  • 数据分析分段折线图
  • 【C++常见错误】0xC0000005: 读取位置 0x00000000 时发生访问冲突
  • .Net的潘多拉魔盒开箱即用,你学废了吗?
  • 【面经】2024年软件测试面试题,精选100 道(附答案)
  • OpenGauss学习笔记