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