一个扑克牌洗牌的实例代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RandomNumber
{
public class RandomCreater
{
// 随机数生成器只需要一个
private static readonly System.Random random = new Random();
public int[] Random(int[] array)
{
int length = array.Length;
for (int i = 0; i < length - 1; i++)
{
// 随机生成准备交换的下标
int index = random.Next(i + 1, length);
// 与当前的数字进行交换
int t = array[i];
array[i] = array[index];
array[index] = t;
}
return array;
}
}
class Program
{
static void Main(string[] args)
{
// 首先创建一个有序的数组
int[] array = new int[54];
for (int i = 0; i < 54; i++)
array[i] = i + 1;
// 进行随机处理
RandomCreater rc = new RandomCreater();
int[] randomArray = rc.Random(array);
// 输出
for (int i = 0; i < randomArray.Length; i++)
Console.Write("{0} ", randomArray[i]);
Console.WriteLine();
Console.Read();
}
}
}