方法1:创建一个新的数组,每次从原本数组中随机取一个数放到新数组中,每次取出过后就移除原本数组中的元素,数组长度有多少就执行长度-1次。
方法2:直接根据数组的长度生成随机数,每次生成的随机数用来当做交换数据的加标,比如第一次生成随机数5,就把下标1和下标5的数据交换顺序即可,这样就能打乱数组的顺序了。
这里介绍第二种的代码:
using System;
namespace 打乱数组顺序
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] result = Disrupted(nums);
Console.WriteLine("打乱后的数组:");
for (int i = 0; i < result.Length; i++)
{
Console.Write(result[i] + " ");
}
int[] Disrupted(int[] nums)
{
for (int i = 0; i < nums.Length; i++)
{
int j = new Random().Next(i, nums.Length);
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
return nums;
}
}
}
}
输出