简体   繁体   English

如何轻松随机化数组?

[英]How to easily randomize an array?

After my last question completely died I would like to ask a question: 在我的最后一个问题完全消失之后,我想问一个问题:

How could I EASILY implement an array randomizer into my code: 如何在我的代码中轻松实现数组随机化器:

private void button9_Click(object sender, EventArgs e)
{
    axSkype1.CurrentUserProfile.MoodText = ();
}

This is my code and I'm using the skype4comlib so don't worry but I would like to find a way that I could set the users Skype 'mood' to a random element of an array such as "I am failing at coding, The Slow Brown Sheep jumped over the fox" yea oh and also I'm going to attach this to a 5 min timer but yea I can do that but not the array. 这是我的代码,我使用的是skype4comlib,所以不用担心,但是我想找到一种方法,可以将用户Skype的“心情”设置为数组的随机元素,例如“我在编码时失败,慢棕羊跳过了狐狸,是的,我还要将它附加到5分钟的计时器上,但是可以,但是我不能这样做。

You can use as an index of the array the following expression: new Random().Next(0,SIZE_OF_YOUR_ARRAY) 您可以使用以下表达式作为数组的索引: new Random().Next(0,SIZE_OF_YOUR_ARRAY)

So if your array is called MoodTexts you can use something like that: 因此,如果您的数组称为MoodTexts ,则可以使用如下代码:

String randomText = MoodTexts[new Random().Next(0,MoodTexts.Length)];

    private void button9_Click()
    {
        string messages = "I am failing at coding,The Slow Brown Sheep jumped over the fox,Message3,Message4, Message5";
        string[] messagesArray = messages.Split(new Char[] { ',' });
        axSkype1.CurrentUserProfile.MoodText =messagesArray[new Random().Next(0,messagesArray.Length)].ToString();
    }

or you can use a method to return a random string form a "messages" string: 或者您可以使用一种方法来从“消息”字符串返回随机字符串:

    private void button9_Click()
    {
        string messages = "I am failing at coding,The Slow Brown Sheep jumped over the fox,Message3,Message4,Message5";
        axSkype1.CurrentUserProfile.MoodText =GetRandomMessage(messages);
    }

    string GetRandomMessage(string messages)
    {
        string[] messagesArray = messages.Split(new Char[] { ',' });
        return messagesArray[new Random().Next(0, messagesArray.Length)].ToString();
    }

or 要么

Create a private member as an instance of the Random class. 创建一个私有成员作为Random类的实例。

var random = new Random ();

Then use it to get a new random number whenever you need one. 然后在需要时使用它来获取一个新的随机数。

random.Next(0, messagesArray.Length)

This will give you back a random number between 0 and the length of your array minus 1, which you can use to randomly index into the array. 这将为您提供一个介于0和数组长度之间的随机数减去1,您可以使用它随机地索引数组。

Creating the single instance of the Random class is important. 创建Random类的单个实例很重要。 If you recreate the Random class over and over, the randomness of the values may not be as random as you'd like. 如果您一遍又一遍地重新创建Random类,则值的随机性可能不会像您想要的那样随机。

https://msdn.microsoft.com/en-us/library/system.random.aspx https://msdn.microsoft.com/zh-CN/library/system.random.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM