C#完成將數組內元素打亂次序的辦法。本站提示廣大學習愛好者:(C#完成將數組內元素打亂次序的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成將數組內元素打亂次序的辦法正文
本文實例講述了C#完成將數組內元素打亂次序的辦法。分享給年夜家供年夜家參考。詳細以下:
1.泛型類代碼
//泛型類
class Item<T>
{
T[] item;
//結構函數
public Item(T[] obj)
{
item = new T[obj.Length];
for (int i = 0; i < obj.Length; i++)
{
item[i] = obj[i];
}
}
public Type ShowType() { return typeof(T); } //前往類型
public T[] GetItems() { return item; } //前往原數組
//前往打亂次序後的數組
public T[] GetDisruptedItems()
{
//生成一個新數組:用於在之上盤算和前往
T[] temp;
temp = new T[item.Length];
for (int i = 0; i < temp.Length; i++) { temp[i] = item[i]; }
//打亂數組中元素次序
Random rand = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < temp.Length; i++)
{
int x, y; T t;
x = rand.Next(0, temp.Length);
do
{
y = rand.Next(0, temp.Length);
} while (y == x);
t = temp[x];
temp[x] = temp[y];
temp[y] = t;
}
return temp;
}
}
2.Main函數挪用
static void Main(string[] args)
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//輸入數組類型
Item<int> disrupter = new Item<int>(array);
Console.WriteLine("數組類型:" + disrupter.ShowType().ToString());
//輸入數組
Console.Write("原輸出數組為:");
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i].ToString() + ' ');
}
Console.WriteLine();
//輸入一個打亂後數組
int[] disruptedArray = disrupter.GetDisruptedItems();
Console.Write("打亂後數組為:");
for (int i = 0; i < disruptedArray.Length; i++)
{
Console.Write(disruptedArray[i].ToString() + ' ');
}
Console.WriteLine();
Console.ReadLine();
}
3.運轉成果

願望本文所述對年夜家的C#法式設計有所贊助。