如何在c中生成唯一的随机数字#
问题描述:
大家好我正在创建一个叫做Quiz游戏的程序。现在我的问题是如何产生一个不重复的问题?我所有的问题都存储在switch语句中。我试过并搜索了所有可能的解决方案,但仍然得到相同的输出结果。我的下面的代码只是一个样本,我没有粘贴它所有的bcoz它太长。每当我调用Question()方法时,它都会随机,但有时候已经问过的问题正在被再次提问。如何在c中生成唯一的随机数字#
public void Question()
{
var random = new Random((int)DateTime.Now.Ticks);
var randomValue = random.Next(1, 8);
switch (randomValue)
{
case 1:
ans = 1;
btnA.Visible = true;
btnB.Visible = true;
btnC.Visible = true;
btnD.Visible = true;
btn50.Enabled = true;
btndoubledip.Enabled = true;
lblQuestion.Text = "1+1=?";
voice = new SpeechSynthesizer();
voice.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Child);
voice.SpeakAsync(lblQuestion.Text.ToString());
btnA.Text = "2";
btnB.Text = "1";
btnC.Text = "4";
btnD.Text = "5";
}
break;
答
使用Randomize a List<T>来洗牌清单。所以:
private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
然后只是洗刷你的问题清单,并显示它们从头到尾。
List<Question> questions = new List<Question>()
{
question1,
question2,
question3
//...
}
questions.Shuffle();
foreach (Question question in questions) question.Ask();
+0
Fisher-Yates shuffle incase有人想读更多关于算法,它非常酷! –
我甚至不认为你的发布代码会编译。 – maccettura
你真的在错误地思考这个问题。首先,不要使用switch语句 - 将问题保存在List中,随机排列列表(在Stack Overflow上执行该操作的方法很多),然后按照新的顺序遍历它们。 – DavidG
你将需要以某种方式存储已经问过的问题列表。或者在选择另一个问题之前存储问题列表并从中删除项目。 –