我正在尝试随机化字符串元素,但我的代码正在重复字符串。有人可以解释我的代码有什么问题吗?
string[] words = Console.ReadLine().Split();
//input = "Welcome and have fun learning programming"
Random number = new Random();
for (int i = 0; i < words.Length; i++)
{
int currRandomNumber = number.Next(0, words.Length);
words[i] = words[currRandomNumber];
}
Console.WriteLine(string.Join(' ', words));
//output = "have learning learning learning learning programming"
我遇到单词重复的问题,而且不是随机的?如果您不明白我的意思,请参阅我在代码中添加的注释。任何帮助将不胜感激!
最佳答案
这些话在重复,因为你正在这样做:
words[i] = words[currRandomNumber];
该行的意思是“将索引
currRandomNumber
处的单词复制到索引 i
”。只要 i
和 currRandomNumber
不同,就保证有重复的词。您的意思可能是交换
currRandomNumber
和 i
处的单词:var temp = words[i];
words[i] = words[currRandomNumber];
words[currRandomNumber] = temp;
// in C# 7, you could swap two values very easily by:
// (words[currRandomNumber], words[i]) = (words[i], words[currRandomNumber]);
或者,您可以使用 Fisher Yates shuffling algorithm ,以确保每个排列发生的机会均等:
static void Shuffle<T>(T[] array)
{
int n = array.Length;
for (int i = 0; i < n; i++)
{
int r = i + _random.Next(n - i);
T t = array[r];
array[r] = array[i];
array[i] = t;
}
}
// Shuffle(words);
关于c# - 在 C# 中随机化字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55204853/