• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Random类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Random的典型用法代码示例。如果您正苦于以下问题:C# Random类的具体用法?C# Random怎么用?C# Random使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Random类属于命名空间,在下文中一共展示了Random类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        n = Convert.ToInt32(Session["n"]);//Convert.ToInt32(n_txt.Text);
        dx = Convert.ToInt32(Session["dx"]);//Convert.ToInt32(n_txt.Text);
        dy = Convert.ToInt32(Session["dy"]);//Convert.ToInt32(n_txt.Text);
        npow = Convert.ToInt32(Math.Pow(2, n));
        boxes = new int[npow, npow,2];
        //if (!IsPostBack)
        {
            if (Session["create"].ToString() != "1")
            {
                Random rnd = new Random();
                for (int i = 0; i <= boxes.GetUpperBound(0); i++)
                {
                    for (int k = 0; k <= boxes.GetUpperBound(1); k++)
                    {
                        boxes[i, k, 0] = rnd.Next(1, 6);
                    }
                }
            }
            else
            {
               
                CreateBoxes(true, 0, 0, boxes.GetUpperBound(0), boxes.GetUpperBound(1),dx,dy);
            }

            fillBoxPanel();
        }

    }
开发者ID:damla-ahmet,项目名称:bin-packing-algorithm,代码行数:30,代码来源:box.aspx.cs


示例2: GenerateRandomCode

 // Function to generate random string with Random class.
 private string GenerateRandomCode()
 {
     Random r = new Random();
     string s = "";
     for (int j = 0; j < 5;j++)
     {
         int i = r.Next(3);
         int ch;
         switch (i)
         {
             case 1:
                 ch = r.Next(0, 9);
                 s = s + ch.ToString();
                 break;
             case 2:
                 ch = r.Next(65, 90);
                 s = s + Convert.ToChar(ch).ToString();
                 break;
             case 3:
                 ch = r.Next(97, 122);
                 s = s + Convert.ToChar(ch).ToString();
                 break;
             default:
                 ch = r.Next(97, 122);
                 s = s + Convert.ToChar(ch).ToString();
                 break;
         }
         r.NextDouble();
         r.Next(100, 1999);
     }
     return s;
 }
开发者ID:shjelm,项目名称:TopicMaster,代码行数:33,代码来源:CImage.aspx.cs


示例3: AutoGeneratedPassword

    public static string AutoGeneratedPassword(string sEMail)
    {
        string sRondomPassword;

        sRondomPassword = string.Empty;
        Random oRandom = new Random();

        //  6 Characters Password...
        for (int iRunner = 0; iRunner < 6; iRunner++)
        {
            int iRandom = oRandom.Next(0, 61);
            sRondomPassword = sRondomPassword + PassChars.Substring(iRandom, 1);
        }

        //  Get PassKey from Session
        string sPassKey = PassKey;

        //  Get Encrypted Password...
        //string sCryptedPassword = CreatePasswordHash(sPassword);

        object ErrorMessage;
        UserInfo oUser = new UserInfo();

        bool UserCreated = oUser.ResetSiteUserPassword(sEMail, sRondomPassword, out ErrorMessage);
        oUser = null;

        //  Function Returning New Password
        return sRondomPassword;
    }
开发者ID:projectrefer,项目名称:JooteyWalaApp,代码行数:29,代码来源:UserSession.cs


示例4: PosTest1

    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Double value equals with Equals(Double).");

        try
        {
            Double d1 = new Random(-55).NextDouble();
            Double d2 = d1;

            if (!d1.Equals(d2))
            {
                TestLibrary.TestFramework.LogError("001.1", "Method Double.Equals(Double) Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:26,代码来源:doubleequals1.cs


示例5: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        OpenFlashChart.OpenFlashChart chart = new OpenFlashChart.OpenFlashChart();
        chart.Title=new Title("AreaHollow");

        AreaHollow area = new AreaHollow();
        Random random=new Random();
        area.Colour = "#0fe";
        area.DotSize = 2;
        area.FillAlpha = 0.4;
        area.Text = "Test";
        area.Width = 2;
        area.FontSize = 10;
        IList values = new List<double>();
        for (int i = 0; i < 12; i++)
            values.Add(random.Next(i, i*2));
        area.Values = values;
        chart.AddElement(area);
         XAxis xaxis=new XAxis();
           // xaxis.Labels = new AxisLabel("text","#ef0",10,"vertical");
        xaxis.Steps = 1;
        xaxis.SetRange(0,12);
        chart.X_Axis = xaxis;
        YAxis yaxis = new YAxis();
        yaxis.Steps = 4;
           yaxis.SetRange(0,20);
        chart.Y_Axis = yaxis;
        string s = chart.ToString();
        Response.Clear();
        Response.CacheControl = "no-cache";
        Response.Write(s);
        Response.End();
    }
开发者ID:gamineiro,项目名称:open-flash-chart-tip-image,代码行数:33,代码来源:chart1.aspx.cs


示例6: GenerateSMP

    /// <summary>
    /// 生成手机密码:通过用户编号
    /// </summary>
    /// <param name="sUserNo">用户编号</param>
    /// <returns>已生成手机密码的用户的手机号</returns>
    public string GenerateSMP(string sUserNo)
    {
        Random r1 = new Random();
        int iRandomPassword;
        string sRandomPassword,SM_content,mobile_telephone,sOperCode;
        DataSet ds=new DataSet();

        //生成密码
        iRandomPassword = r1.Next(1000000);
        sRandomPassword = fu.PasswordEncode(iRandomPassword.ToString());
        ds = fu.GetOneUserByUserIndex(sUserNo);

        sOperCode = ds.Tables[0].Rows[0]["User_code"].ToString();
        mobile_telephone = ds.Tables[0].Rows[0]["mobile_telephone"].ToString();

        sSql = "UPDATE Frame_user SET SM_PWD='" + sRandomPassword + "',SMP_last_change_time=getdate()" +
                " WHERE User_code = '" + sOperCode + "'";
        sv.ExecuteSql(sSql);
        //发送密码

        string SMP_validity_period = ds.Tables[0].Rows[0]["SMP_validity_period"].ToString();
        SM_content = "欢迎您使用EBM系统!您新的手机密码是:" + iRandomPassword.ToString() + "有效时间为:" + SMP_validity_period + "小时。";
        SendSMContentByPhoneCode(mobile_telephone, SM_content);
        return mobile_telephone;
    }
开发者ID:pjjwpc,项目名称:GrainDepot,代码行数:30,代码来源:Frame_SMS.cs


示例7: SetRandomEdge

        public static void SetRandomEdge(int[,] graph, int n)
        {
            bool found = false;
            int i = 0;
            int j = 0;

            int count = 0;
            Random random = new Random();

            for (int k = 0; k < n; k++)
            {
                for (int l = 0; l < n; l++)
                {
                    if (graph[k, l] != int.MaxValue)
                        continue;

                    count++;

                    if (random.Next(0, count) == 0)
                    {
                        found = true;
                        i = k;
                        j = l;
                    }
                }
            }

            if (found)
                graph[i, j] = random.Next(1, 10);
        }
开发者ID:mmoroney,项目名称:Algorithms,代码行数:30,代码来源:GraphUtilities.cs


示例8: Main

    // You are given an array of strings. Write a method
    // that sorts the array by the length of its elements
    // (the number of characters composing them).

    static void Main()
    {
        //variables
        string[] array = new string[7];
        Random rand = new Random();

        //fill the Array with Random strings
        for (int i = 0; i < array.Length; i++)
        {
            string member = null;
            for (int k = 0; k < rand.Next(1, 7); k++)     //length of strings
            {
                member = member + RandomString();
            }
            array[i] = member;
        }

        #region print original array
        Console.Write("{");
        Console.Write(String.Join(", ", array));
        Console.WriteLine("} -> ");
        #endregion

        //sort the array by the length of its elements
        var SortedArray = array.OrderBy(x => x.Length);     //using Linq

        #region print sorted array
        Console.Write("{");
        Console.Write(String.Join(", ", SortedArray));
        Console.WriteLine("} ");
        #endregion
    }
开发者ID:niki-funky,项目名称:Telerik_Academy,代码行数:36,代码来源:05.+SortingArrayOfStrings.cs


示例9: GuessGame

    // guessGame receives user input and returns output
    // based on their guess.
    private static void GuessGame(object obj)
    {
        var client = (TcpClient)obj;
        NetworkStream stream = client.GetStream();
        StreamReader streamR = new StreamReader(stream);
        StreamWriter streamW = new StreamWriter(stream);
        streamW.AutoFlush = true;

        string input;
        int guess = 0;
        int guesses = 0;
        int num = new Random().Next(1, 101);

        try {
            streamW.WriteLine("+ Hello. I'm thinking of a number between 1 and 100. Can you guess it?");
            while(guess != num) {
                input = streamR.ReadLine();
                guesses++;
                if (!int.TryParse(input, out guess) || (guess < 1 || guess > 100)) {
                    guesses--;
                    streamW.WriteLine("! Invalid input, please enter only numbers between 1 and 100.");
                } else if (guess < num) {
                    streamW.WriteLine("> Higher.");
                } else if (guess > num) {
                    streamW.WriteLine("< My number is lower.");
                }
            }
            streamW.WriteLine("* That's it. Good job. It took you {0} guesses. Thanks for playing.", guesses);
            stream.Close();
        } catch (Exception) {
            stream.Close();
            return;
        }
    }
开发者ID:richmt,项目名称:NumGameServer,代码行数:36,代码来源:NumGameServer.cs


示例10: CreateImage

    /// <summary>
    /// ����ͼƬ
    /// </summary>
    /// <param name="checkCode">�����</param>
    private void CreateImage(string checkCode)
    {
        int iwidth = (int)(checkCode.Length * 11.5);//����������趨ͼƬ���
        Bitmap image = new Bitmap(iwidth, 20);//����һ������
        Graphics g = Graphics.FromImage(image);//�ڻ����϶����ͼ��ʵ��
        Font f = new Font("Arial",10,FontStyle.Bold);//���壬��С����ʽ
        Brush b = new SolidBrush(Color.Black);//������ɫ
        //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
        g.Clear(Color.White);//������ɫ
        g.DrawString(checkCode, f, b, 3, 3);

        Pen blackPen = new Pen(Color.Black, 0);
        Random rand = new Random();
        /*�����
        for (int i = 0; i < 5; i++)
        {
            int y = rand.Next(image.Height);
            g.DrawLine(blackPen, 0, y, image.Width, y);
        }
        */
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        Response.ClearContent();
        Response.ContentType = "image/Jpeg";
        Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        image.Dispose();
    }
开发者ID:vtmer,项目名称:NewStudent,代码行数:32,代码来源:checkCode.aspx.cs


示例11: MultipleAnnounce

        public void MultipleAnnounce()
        {
            var announceCount = 0;
            var random = new Random();
            var handle = new ManualResetEvent(false);

            for (var i = 0; i < 20; i++)
            {
                var infoHash = new InfoHash(new byte[20]);
                random.NextBytes(infoHash.Hash);
                var tier = new TrackerTier(new[] {_uri.ToString()});
                tier.Trackers[0].AnnounceComplete += (sender, args) =>
                                                         {
                                                             if (++announceCount == 20)
                                                                 handle.Set();
                                                         };
                var id = new TrackerConnectionID(tier.Trackers[0], false, TorrentEvent.Started,
                                                 new ManualResetEvent(false));
                var parameters = new OctoTorrent.Client.Tracker.AnnounceParameters(0, 0, 0, TorrentEvent.Started,
                                                                                   infoHash, false, new string('1', 20),
                                                                                   string.Empty, 1411);
                tier.Trackers[0].Announce(parameters, id);
            }

            Assert.IsTrue(handle.WaitOne(5000, true), "Some of the responses weren't received");
        }
开发者ID:mrscylla,项目名称:octotorrent,代码行数:26,代码来源:TrackerTests.cs


示例12: RandomStringArray

    static string[] RandomStringArray()
    {
        Random rand = new Random();
        int len = rand.Next(3, 10); // [3;10)
        string[] stringArr = new string[len];

        // let's build the words observing the frequency of the letters in English
        // so for example the vowels will appear more often
        // http://www.oxforddictionaries.com/words/what-is-the-frequency-of-the-letters-of-the-alphabet-in-english
        double[] frequencies = { 0.002, 0.004, 0.007, 0.010, 0.020, 0.031, 0.044, 0.061, 0.079, 0.100, 0.125, 0.155, 0.185, 0.217, 0.251, 0.287, 0.332, 0.387, 0.444, 0.511, 0.581, 0.652, 0.728, 0.803, 0.888, 1.000, };
        char[] letters = { 'q', 'j', 'z', 'x', 'v', 'k', 'w', 'y', 'f', 'b', 'g', 'h', 'm', 'p', 'd', 'u', 'c', 'l', 's', 'n', 't', 'o', 'i', 'r', 'a', 'e', };

        for (int i = 0; i < len; i++)
        {
            int wordLen = rand.Next(1, 10); // determines the length of the current string
            string word = string.Empty;
            for (int j = 0; j < wordLen; j++)
            {
                double frequency = rand.Next(2, 1000) / 1000d; // [0.002;0.999]
                int index = Array.BinarySearch(frequencies, frequency);
                if (index < 0) index = ~index;
                char letter = letters[index];
                word += letter;
            }
            stringArr[i] = word;
        }
        return stringArr;
    }
开发者ID:MarKamenov,项目名称:TelerikAcademy,代码行数:28,代码来源:SortByLen.cs


示例13: BtnAdd_Click

    protected void BtnAdd_Click(object sender, EventArgs e)
    {
        SqlConnection vid = new SqlConnection("Data Source=(local);Initial Catalog=Ring;Integrated Security=True");
        {
            Random rnd = new Random();
            SqlCommand orders = new SqlCommand("INSERT INTO dbo.orders (email,order_ID,month,year,jewel_ID,price,credit_Card) VALUES (@email,@order_ID,@month,@year,@jewel_ID,@price,@credit_Card)", vid);
            orders.Parameters.AddWithValue("@email", Session["username"]);
            int holder = rnd.Next(10000000,99999999);
            orders.Parameters.AddWithValue("@price", ddlPrice.Text);
            orders.Parameters.AddWithValue("@jewel_ID", ddlJewel.Text);
            holder = rnd.Next(10000000, 99999999);
            orders.Parameters.AddWithValue("@order_ID", holder.ToString());
            orders.Parameters.AddWithValue("@month", DateTime.Now.Month.ToString());
            orders.Parameters.AddWithValue("@year", DateTime.Now.Year.ToString());
            holder = rnd.Next(10000000, 99999999);
            orders.Parameters.AddWithValue("@credit_Card", holder.ToString());
            holder = rnd.Next(10000000, 99999999);
            SqlCommand inventory = new SqlCommand("UDATE dbo.Inventory SET jewel_ID='"+holder+"'WHERE jewel_ID='"+ ddlJewel.Text+"'", vid);
            vid.Open();

            orders.ExecuteNonQuery();
            inventory.ExecuteNonQuery();
            vid.Close();

            if (IsPostBack)
            {
                Server.Transfer("Account.aspx", true);
            }
        }
    }
开发者ID:PyViet,项目名称:Ring-Database,代码行数:30,代码来源:Browse.aspx.cs


示例14: CreateJToken

        private static JToken CreateJToken(Random rndGen, int depth)
        {
            if (rndGen.Next() < CreatorSettings.NullValueProbability)
            {
                return null;
            }

            if (depth < MaxDepth)
            {
                switch (rndGen.Next(10))
                {
                    case 0:
                    case 1:
                    case 2:
                        // 30% chance to create an array
                        return CreateJArray(rndGen, depth);
                    case 3:
                    case 4:
                    case 5:
                        // 30% chance to create an object
                        return CreateJObject(rndGen, depth);
                    default:
                        // 40% chance to create a primitive
                        break;
                }
            }

            return CreateJsonPrimitive(rndGen);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:29,代码来源:JsonValueCreatorSurrogate.cs


示例15: Run

 public override async Task Run()
 {
     int itemId, amount;
     if (HasQuestStarted(2051))
     {
         itemId = 4031032;
         amount = 1;
     }
     else
     {
         int[] rewards = new[] {
             4020007, 2,
             4020008, 2,
             4010006, 2,
             1032013, 1
         };
         var rand = new Random();
         int index = rand.Next(rewards.Length / 2);
         itemId = rewards[index];
         amount = rewards[index + 1];
     }
     if (GainItem(itemId, amount))
     {
         SetField(101000000);
     }
     else
     {
         //TODO: Make more GMS-like.
         Talker.Notify("Please check whether your ETC. inventory is full.");
     }
 }
开发者ID:Tagette,项目名称:WvsNpcSimulator,代码行数:31,代码来源:bush2.cs


示例16: reset

        public void reset()
        {
            Random random = new Random();
            int localtag = 0;
            localtag++;

            // TO TRIGGER THE BUG:
            // remove the itself from parent from an action
            // The menu will be removed, but the instance will be alive
            // and then a new node will be allocated occupying the memory.
            // => CRASH BOOM BANG
            CCNode node = getChildByTag(localtag - 1);
            CCLog.Log("Menu: %p", node);
            removeChild(node, false);
            //	[self removeChildByTag:localtag-1 cleanup:NO];

            CCMenuItem item1 = CCMenuItemFont.itemFromString("One", this, menuCallback);
            CCLog.Log("MenuItemFont: %p", item1);
            CCMenuItem item2 = CCMenuItemFont.itemFromString("Two", this, menuCallback);
            CCMenu menu = CCMenu.menuWithItems(item1, item2);
            menu.alignItemsVertically();

            float x = random.Next() * 50;
            float y = random.Next() * 50;
            menu.position = CCPointExtension.ccpAdd(menu.position, new CCPoint(x, y));
            addChild(menu, 0, localtag);

            //[self check:self];
        }
开发者ID:Ratel13,项目名称:cocos2d-x-for-xna,代码行数:29,代码来源:Bug422Layer.cs


示例17: GetRandomPro

    public static ProductsModel GetRandomPro()
    {
        ProductsModel pro = new ProductsModel();
        try
        {

            using (DataContentDataContext dc = new DataContentDataContext())
            {
                var items = (from temp in dc.Products
                             select temp);
                int count = items.Count(); // 1st round-trip
                int index = new Random().Next(count);
                Product i = items.Skip(index).FirstOrDefault();
                ProductsModel p = new ProductsModel(i.Id, i.Header, i.Name, i.Descrition, i.Price, i.Link_Image_Small, i.Link_Image, i.Creater, i.CreateDate, i.Modifier, i.ModifyDate);
                pro = p;

            }
            return pro;
        }
        catch (Exception)
        {
            return pro;

        }
    }
开发者ID:chutinhha,项目名称:spa-pro-web,代码行数:25,代码来源:ProductsViewModel.cs


示例18: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        //加载页面时初始化支付需要的业务明文参数

        orderAmount.Text = "2";//默认的交易金额

        Random ra = new Random();
        traderOrderID.Text = "1234567" + 50 * ra.Next();//商户订单号

        identityID.Text = "user_" + 50 * ra.Next();//用户身份标识
        identityType.Text = "2";//用户身份标识类型,0为IMEI,1为MAC,2为用户ID,3为用户Email,4为用户手机号,5为用户身份证号,6为用户纸质协议单号
        userIP.Text = getIp();//获取用户IP地址
        userUA.Text = Request.UserAgent;//获取用户UA

        terminalType.Text = "3";//终端类型,0、IMEI;1、MAC;2、UUID;3、other,如果终端类型未知的话,那么就传other
        terminalID.Text = "nothing";//终端类型未知,终端标识可以传任意字符串

        productCatalog.Text = "1";//1代表虚拟商品,商品类别必须与协议保持一致。商品类别编码请见http://mobiletest.yeepay.com/file/doc/pubshow?doc_id=14#hm_27。
        productName.Text = "玉米加农炮";//商品名称
        productDesc.Text = "植物大战僵尸道具";//商品描述

        fcallbackURL.Text = "http://mobiletest.yeepay.com/demo/pay/callback";//支付成功后商户前台提供的回调的地址,fcallbackURL.Text = "http://mobiletest.yeepay.com/demo/pay/callback";

        callbackURL.Text = "http://mobiletest.yeepay.com/demo/pay/callback";//支付成功后商户后台提供的回调的地址,fcallbackURL.Text = "http://mobiletest.yeepay.com/demo/pay/callback";
    }
开发者ID:cangjie,项目名称:lq_yeepay,代码行数:25,代码来源:PCPay.aspx.cs


示例19: RunTests

        public static void RunTests(int seed)
        {
            Random random = new Random(seed);

            RunPositiveTests(random);
            RunNegativeTests(random);
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:7,代码来源:Comparison.cs


示例20: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        var theData = new List<string>();

        Random rand = new Random();
        Response.Write("<br><br>Adding items to the list, ");
        for (int i = 0; i < 999; i++)
            theData.Add("Item" + (i + rand.Next(100)).ToString("0000"));

        Response.Write("<br><br>Finding " + theData[theData.Count / 2]);
        var findItem = from p in theData
                       where p == theData[theData.Count / 2]
                          select p;

        Response.Write(" : Found Total " + findItem.Count());

        Response.Write("<br><br>Listing First 10 Items: ");
        for (int i = 0; i < 10; i++)
            Response.Write(theData[i] + ", ");

        theData.Sort();
        Response.Write("<br><br>Listing First 10 Items after sort: ");
        for (int i = 0; i < 10; i++)
            Response.Write(theData[i] + ", ");
    }
开发者ID:kingkongkbf,项目名称:AdvASPdotNetCourse,代码行数:25,代码来源:expressiontrees.aspx.cs



注:本文中的Random类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# RandomGenerator类代码示例发布时间:2022-05-24
下一篇:
C# RakudoObject类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap