亂數產生函式彙整

亂數產生函式彙整

參考了下列資料

取得亂數所產生的英文字母大小寫與數字組合的字串

[VBA] 演算法 - 亂數 不重複

[c#] 亂數不重複

[C#]產生不重複的編號-Guid

整理一下


using System.Collections.Generic;
using System.Text;



public class RanGenerator
{
    #region 亂數函數處理
    /// <summary>
    /// 取得亂數所產生的英文字母大小寫與數字組合的字串,-1表示不隨機產生
    /// </summary>
    /// <param name="length">要產生的亂數字串長度</param>
    /// <param name="seed">亂數種子隨索引改變</param>
    /// <returns>亂數字串</returns>
    public static string GetRandomString(int length, int seed)
    {
        try
        {
            Random r;
            if (seed.ToString() == "-1")
                r = new Random();
            else
                r = new Random(DateTime.Now.Millisecond + seed);
            string code = "";
            for (int i = 0; i < length; i++)
            {
                switch (r.Next(0, 3))
                {
                    case 0: code += r.Next(0, 10); break;
                    case 1: code += (char)r.Next(65, 91); break;
                    case 2: code += (char)r.Next(97, 122); break;

                }
            }
            return code;
        }
        catch (Exception e)
        {
            return null;
        }
    }
    /// <summary>
    /// 取得亂數所產生的BIG5中文字組合的字串,-1表示不隨機產生種子
    /// </summary>
    /// <param name="length">要產生的亂數字串長度</param>
    /// <param name="seed">亂數種子隨索引改變</param>
    /// <returns>亂數字串</returns>
    public static string GetRandomChiString(int length, int seed)
    {
        try
        {
            Random r;
            if (seed.ToString() == "-1")
                r = new Random();
            else
                r = new Random(DateTime.Now.Millisecond + seed);
            byte[] codetemp = new byte[2 * length];
            for (int i = 0; i < 2 * length; i += 2)
            {
                bool cont = true;
                do
                {
                    codetemp[i] = (byte)r.Next(0, 255);
                    codetemp[i + 1] = (byte)r.Next(0, 255);
                    byte[] temp1 = new byte[2] { codetemp[i], codetemp[i + 1] };
                    string temp2 = Encoding.GetEncoding("Big5").GetString(temp1);
                    int iCode = codetemp[i] * 256 + codetemp[i + 1];

                    if ((iCode >= 42048 && iCode <= 50814) || (iCode >= 51520 && iCode <= 63957))
                    {
                        if (temp2 == "?")

                            cont = true;
                        else
                            // chinese char big5 
                            cont = false;
                    }
                    else cont = true;

                } while (cont == true);
            }
            string strResult = Encoding.GetEncoding("Big5").GetString(codetemp);
            return strResult;
        }
        catch (Exception e)
        {            
            return null;
        }
    }

    /// <summary>
    /// Makes the rand no duplicate.
    /// </summary>
    /// <param name="intLower">The int lower.</param>
    /// <param name="intUpper">The int upper.</param>
    /// <param name="intNum">The int num.</param>
    /// <returns></returns>
    public static System.Collections.ArrayList MakeRandNoDuplicate(int intLower, int intUpper, int intNum)
    {

        /* 用法
         * private void btnMakeRand_Click(object sender, EventArgs e) 
         { 
            // txtLower 為 TextBox 控制項,讓使用者輸入亂數範圍下限 
            // txtUpper 為 TextBox 控制項,讓使用者輸入亂數範圍上限 
            // txtNum   為 TextBox 控制項,讓使用者輸入亂數範圍數量 
            lstboxRand.Items.Clear(); 
            System.Collections.ArrayList rnd = MakeRand(int.Parse(txtLower.Text), int.Parse(txtUpper.Text), int.Parse(txtNum.Text)); 
            lstboxRand.Items.AddRange(rnd.ToArray()); 
         }*/
        try
        {
            if (intNum > (intUpper - intLower + 1))
                return null;
            else if (intLower > intUpper)
                return null;
            else
            {
                System.Collections.ArrayList arrayRand = new System.Collections.ArrayList();
                Random random = new Random((int)DateTime.Now.Ticks);
                int intRnd;
                while (arrayRand.Count < intNum)
                {
                    intRnd = random.Next(intLower, intUpper + 1);
                    if (!arrayRand.Contains(intRnd))
                    {
                        arrayRand.Add(intRnd);
                    }
                }
                return arrayRand;
            }
        }
        catch (Exception e)
        {
            System.Collections.ArrayList arrayRand = new System.Collections.ArrayList();
            return arrayRand;
        }
    }

    /// <summary>
    /// Randoms the specified rand.
    /// </summary>
    /// <param name="rand">The rand.</param>
    /// <returns></returns>
    public static int random(int rand)
    {
        try
        {
            if (rand < 1)
                return 0;
            Random random = new Random(DateTime.Now.Millisecond);
            return random.Next(rand);
        }
        catch (Exception e)
        {
            return 0;
        }
    }


    /// <summary>
    /// Rands the num.
    /// </summary>
    /// <param name="TotalNumber">The total number.</param>
    /// <param name="choose">The choose.</param>
    /// <returns></returns>

    public static List<string> RandNum(int TotalNumber, string choose)
    {
        try
        {
            List<string> result = new List<string>();
            switch (choose)
            {
                case "N": for (int i = 0; i < TotalNumber; i++)//32 位數字
                        result.Add(System.Guid.NewGuid().ToString("N"));
                    break;
                case "D": for (int i = 0; i < TotalNumber; i++)//以連字號分隔的 32 位數字
                        result.Add(System.Guid.NewGuid().ToString("D"));
                    break;
                case "B": for (int i = 0; i < TotalNumber; i++)//以連字號分隔並以大括號括起來的 32 位數字
                        result.Add(System.Guid.NewGuid().ToString("B"));
                    break;
                case "P": for (int i = 0; i < TotalNumber; i++)//以連字號分隔並以括號括起來的 32 位數字
                        result.Add(System.Guid.NewGuid().ToString("P"));
                    break;
                default: break;
            }
            return result;
        }
        catch (Exception e)
        {
            return null;
        }
    }
    /// <summary>
    /// 產生亂數。
    /// </summary>
    /// <param name="start">起始數字。</param>
    /// <param name="end">結束數字。</param>        
    public static int[] GenerateRandom(int start, int end)
    {
        int iLength = end - start + 1;
        int[] arrList = new int[iLength];
        for (int N1 = 0; N1 < iLength; N1++)
        {
            arrList[N1] = N1 + start;
        }

        arrList = Shuffle<int>(arrList);
        return arrList;
    }

    //洗牌。
    public static T[] Shuffle<T>(IEnumerable<T> values)
    {
        List<T> list = new List<T>(values);
        T tmp;
        int iS;
        Random r = new Random();
        for (int N1 = 0; N1 < list.Count; N1++)
        {
            iS = r.Next(N1, list.Count);
            tmp = list[N1];
            list[N1] = list[iS];
            list[iS] = tmp;
        }
        return list.ToArray();
    }
    #endregion

}