C#實現(xiàn)將數(shù)組內(nèi)元素打亂順序的方法
更新時間:2015年08月14日 15:12:33 作者:北風其涼
這篇文章主要介紹了C#實現(xiàn)將數(shù)組內(nèi)元素打亂順序的方法,涉及C#數(shù)組遍歷及隨機數(shù)操作的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#實現(xiàn)將數(shù)組內(nèi)元素打亂順序的方法。分享給大家供大家參考。具體如下:
1.泛型類代碼
//泛型類
class Item<T>
{
T[] item;
//構(gòu)造函數(shù)
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; } //返回原數(shù)組
//返回打亂順序后的數(shù)組
public T[] GetDisruptedItems()
{
//生成一個新數(shù)組:用于在之上計算和返回
T[] temp;
temp = new T[item.Length];
for (int i = 0; i < temp.Length; i++) { temp[i] = item[i]; }
//打亂數(shù)組中元素順序
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函數(shù)調(diào)用
static void Main(string[] args)
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//輸出數(shù)組類型
Item<int> disrupter = new Item<int>(array);
Console.WriteLine("數(shù)組類型:" + disrupter.ShowType().ToString());
//輸出數(shù)組
Console.Write("原輸入數(shù)組為:");
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i].ToString() + ' ');
}
Console.WriteLine();
//輸出一個打亂后數(shù)組
int[] disruptedArray = disrupter.GetDisruptedItems();
Console.Write("打亂后數(shù)組為:");
for (int i = 0; i < disruptedArray.Length; i++)
{
Console.Write(disruptedArray[i].ToString() + ' ');
}
Console.WriteLine();
Console.ReadLine();
}
3.運行結(jié)果

希望本文所述對大家的C#程序設計有所幫助。
您可能感興趣的文章:
相關(guān)文章
C#使用opencv截取旋轉(zhuǎn)矩形區(qū)域圖像的實現(xiàn)示例
這篇文章主要介紹了C#使用opencv截取旋轉(zhuǎn)矩形區(qū)域圖像,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03
c#方法中調(diào)用參數(shù)的值傳遞方式和引用傳遞方式以及ref與out的區(qū)別深入解析
以下是對c#方法中調(diào)用參數(shù)的值傳遞方式和引用傳遞方式,以及ref與out的區(qū)進行了詳細的分析介紹,需要的朋友可以過來參考下2013-07-07
C#實現(xiàn)讀取被進程占用的文件實現(xiàn)方法
這篇文章主要介紹了C#實現(xiàn)讀取被進程占用的文件實現(xiàn)方法,涉及C#進程操作及文件讀取的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08

