我正在尝试将字符串元素随机化,但是我的代码正在重复字符串。有人可以解释我的代码有什么问题吗?
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"
我遇到重复单词的问题,它不是随机的吗?如果您不明白我的意思,请参阅我在代码中添加的注释。任何帮助将不胜感激!
答案 0 :(得分:5)
重复这些单词是因为您正在这样做:
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);
答案 1 :(得分:2)
或者,您可以将每个单词以随机顺序放入新列表中:
List<string> words = Console.ReadLine().Split().ToList();
//input = "Welcome and have fun learning programming"
Random number = new Random();
var newwords = new List<string> ();
while (words.Count > 0)
{
int currRandomNumber = number.Next(0, words.Count);
newwords.Add( words[currRandomNumber]);
words.RemoveAt(currRandomNumber);
}
Console.WriteLine(string.Join(' ', newwords));