c# - 如何检查是否存在相同的随机对象
问题描述
我正在做简单的 Xamarin.Forms 益智游戏,我需要 9 个具有不同随机值的谜题。我试图用一些循环检查它,但它仍然无法正常工作。
Random r = new Random();
Label[] puzzles = { puz1, puz2, puz3, puz4, puz5, puz6, puz7, puz8, puz9 };
string[] used = new string[9];
for (int i = 0; i < puzzles.Length; i++)
{
if (i > 0)
{
for (int x = 1; x < used.Length; x++)
{
do
{
puzzles[i].Text = Puzzles.puz[r.Next(0, 8)];
used[x] = puzzles[i].Text;
}
while (used[x - 1] == used[x]);
}
}
else
{
puzzles[i].Text = Puzzles.puz[r.Next(0, 8)];
used[0] = puzzles[i].Text;
}
}
和 Puzzles.cs 类
class Puzzles
{
public static string[] puz = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
}
如何检查新生成的谜题与之前生成的谜题的值不同?
解决方案
这是因为您只检查前面的值是否有重复项,仍然有可能为used[x -2] == used[x]
真。
为了实现您的目标,我建议您实现一个 shuffle 功能,就像您可以在此处找到的那样。它可以给出这样的东西
// Implemented somewhere in your code
private List<E> ShuffleList<E>(List<E> inputList)
{
List<E> randomList = new List<E>();
Random r = new Random();
int randomIndex = 0;
while (inputList.Count > 0)
{
randomIndex = r.Next(0, inputList.Count); //Choose a random object in the list
randomList.Add(inputList[randomIndex]); //add it to the new, random list
inputList.RemoveAt(randomIndex); //remove to avoid duplicates
}
return randomList; //return the new random list
}
// Then for each element of your puzzles array, you could do
puzzles[i].Text = SuffleList(Puzzles.puz);
推荐阅读
- c# - 尝试连接到 RavenDB 时在我的 Azure apim 中出现错误 500
- html - jQuery 句子大小写函数不断替换我的文本
- python - Python Argparse:使用单个大头钉作为标志,例如 `./myscript -5`,如 Git 和 CoreUtils
- sql-server - 我在运行查询时启动了 RDS SQL Server(SQL Server Web 版)并且它抛出了权限被拒绝错误
- python - 如何将 pdf 响应流式传输为文件附件?
- flutter - Flutter 中的权限请求
- python - scrapy splash:连接被对方拒绝:61:连接被拒绝
- android - 相机无法在工作资料上工作 - Xamarin Android
- go - 如何使用 Encore 生成本地客户端
- python - Python:使用多线程运行 eel 会导致错误