c#使用随机生成器为数组分配不同的值

时间:2013-07-22 13:48:14

标签: c#

我有两个叫做数字和声音的数组。我的代码如下。当我使用随机生成器时,我不希望将相同的值分配给声音数组。声音[0],声音[1],声音[3]应始终具有不同的值。谢谢

string[] numbers ={ "1", "2", "3", "4", "5", "6", "7","8","9","10","11","12","13","14","15","16","17","18","19","20"};

Random r= new Random();

sounds[0] = numbers[r.Next(0, numbers.Count())];

sounds[1] = numbers[r.Next(0, numbers.Count())];

sounds[2] = numbers[r.Next(0, numbers.Count())];

2 个答案:

答案 0 :(得分:0)

如果您想要一个简单的方法并且性能不是问题,您可以将数组转换为列表并删除每个元素:

string[] numbers ={ "1", "2", "3", "4", "5", "6", "7","8","9","10","11","12","13","14","15","16","17","18","19","20"};

List<string> remaining = new List<string>(numbers);

Random r = new Random();

for (int i = 0; i < 3; ++i)
{
    int n = r.Next(0, remaining.Count);
    sounds[i] = remaining[n];
    remaining.RemoveAt(n);
}

答案 1 :(得分:0)

这是一个相当简单/天真的答案,可能会给你一些想法。请注意,您应该使用.Length而不是.Count(),因为.Length是O(1)操作,并且您已经拥有该属性。如果sounds更大,则此解决方案不会扩展。如果是这种情况,你会想要改变数字数组。这将为您提供三个独特的值。

string[] numbers = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
string[] sounds = new string[3];
Random r = new Random();

//get the first one, this one will always be unique
sounds[0] = numbers[r.Next(0, numbers.Length)];
//set the second equal to the first, so that it will enter the while loop.
sounds[1] = sounds[0];
while (sounds[1] == sounds[0]) //repeats until it gets a unique value
    sounds[1] = numbers[r.Next(0, numbers.Length)]; 
sounds[2] = sounds[0]; 
while (sounds[2] == sounds[1] || sounds[2] == sounds[0]) //works the same as previous, except it checks for both
    sounds[2] = numbers[r.Next(0, numbers.Length)];