0

我有两个称为数字和声音的数组。我的代码如下。当我使用随机生成器时,我不希望将相同的值分配给声音数组。sound[0]、sounds[1]、sounds[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())];
4

2 回答 2

0

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

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)];
于 2013-07-22T14:00:09.383 回答
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);
}
于 2013-07-22T13:57:26.290 回答