如何随机化变量列表 [英] How do I randomise a list of variables

查看:69
本文介绍了如何随机化变量列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我基本上有一个字符串变量列表,顺序如下。我想要做的基本上是用方法或其他东西随机化这些字符串中的一个,我听说过一些随机方法但与此无关。



Hi,

I have basically a list of string variables in the order of this below. What i am trying to do is basically randomise one of these strings with a method or something, i have heard of some randomise methods but nothing to do with this.

String a;
String b;
String c;
String d;
String e;
String f;
String g;
String h;
String i;





谢谢,我期待从你们其中一个人那里回来。



thanks, and i look forward to hearing back from one of you guys.

推荐答案

创建一个数组,其中索引0代表a,8代表i。现在随机化0到8之间的数字( http:// msdn。 microsoft.com/en-us/library/system.random(v=vs.110).aspx [ ^ ])。在新索引处选择变量...
Create an array where index 0 is for a and 8 is for i. Now randomize a number between 0 to 8 (http://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx[^]). Pick the variable at the new index...


您可以使用随机类来实现此目的

查看下面的代码,它有点粗糙,但应该给你一个基本的想法:

You can use random class for this purpose
Look at the code below, its a little crude, but should give you a basic idea:
string[] s = new string[] {"a","b","c","d","e","f","g","h","i" };
           Random rnd = new Random();

           int i = 0;
           do
           {
               Console.WriteLine("Hit a key .....");
               Console.ReadLine();
               Console.WriteLine(s[rnd.Next(s.Length)]);

           } while (i < s.Length);



看看这段代码,我尝试了另一个场景:


Look at this code also, i have tried another scenario:

string s = "abcdefghi";

           Random rnd = new Random();
           int i = 0;
           do
           {
               Console.WriteLine("Hit a key .....");
               Console.ReadLine();
               Console.WriteLine(s.Substring(rnd.Next(s.Length),1));
                i++;

           } while (i < s.Length);







在第一个代码中,我采用了字符串[],在下一个代码中,我采用了一个字符串:



[ Agent_Spock ]



基本上,随机类用于获取任意2个数字之间的随机数,如上例所示。



谢谢




In the first code i have taken a string[] and in the next code i have taken a single string:

[Agent_Spock]

Basically, random class is used to get a random number between any 2 numbers as shown in the above example.

Thanks


这篇关于如何随机化变量列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆