这是一个相当简单/幼稚的答案,可能会给您一些想法。请注意,您可能应该使用.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)];