c# - 如何从字符串列表中随机提取唯一值?

标签 c#

您好,我是使用 C# 在控制台应用程序中编程的新手。我正在尝试创建一个单词生成器,这是我的代码:

for (int i = 1; i <= 4; i++)
{
    string[] fruits = { "Apple", "Banana", "Grapes", "Orange", "Cherry", "Mango" };
    Random rnd = new Random();
    int rndFruits = rnd.Next(fruits.Length);
    Console.WriteLine(fruits[rndFruits]);
}

我创建了一个字符串列表,然后使用 for 循环将它们随机化以打印四个单词。问题是我不希望它再次重复相同的字符串,就像打印香蕉两次或更多次一样。

最佳答案

这是一个算法。它是这样工作的。 一开始,所有元素对我们来说都是唯一的,因此我们将从 0fruits.Length 中选择一个元素。 选取后,我们将选取的元素与最后一个元素交换。 现在我们知道最后一个元素是我们已知的。现在让我们选择一个从 0fruits.Length -1 的索引。我们不会采取 我们考虑的是最后一个,因为它是我们已知的。同样,在检索索引后,将当前索引处的元素与 fruits.Length -1 处的元素交换, 现在我们对最后两个不感兴趣,依此类推。

string[] fruits = { "Apple", "Banana", "Grapes", "Orange", "Cherry", "Mango" };
Random rnd = new Random();

// This will indicate the last index for which, starting with 0, we will meet only unique elements.
int lastValidStringIndex = fruits.Length;

for (int i = 1; i <= 4; i++)
{
    int rndFruits = rnd.Next(lastValidStringIndex);
    Console.WriteLine(fruits[rndFruits]);

    // place the current element at the end of the list
    string aux = fruits[--lastValidStringIndex];
    fruits[lastValidStringIndex] = fruits[rndFruits];
    fruits[rndFruits] = aux;
}
Little simulation:
string[] fruits = { "Apple", "Banana", "Grapes", "Orange", "Cherry", "Mango" };
Random => "Banana"
Swap banana with Mango

string[] fruits = { "Apple", "Mango", "Grapes", "Orange", "Cherry", | "Banana" };
Random => "Orange"
Swap Orange with Cherry

string[] fruits = { "Apple", "Mango", "Grapes", "Cherry", | "Orange", "Banana" };

and so on

你明白了。我们不检查 |

之后的元素

关于c# - 如何从字符串列表中随机提取唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68910558/

相关文章:

c# - .NET/C# - 将 char[] 转换为字符串

C# for 循环问题

c# - 确定何时使用依赖注入(inject)

c# - 控制对 .NET 程序集的访问

c# - 序列化实现 INotifyPropertyChanged 的​​类的实例时出现 SerializationException

c# - .ASP.NET Core 仅在 Controller 上存在策略时运行策略处理程序

c# - 跨线程操作

c# - 使用 C# 创建新的 Excel 函数(用户定义函数)

c# - 反序列化名称未知的 JSON 对象

c# - 创建泛型类型参数的新实例未获得代码覆盖率