我想知道如何在C#中完成这项任务。例如;
我有10个问题,其中3个将显示给用户 输入答案。如何让程序生成3个问题 假设我们有10个问题,它们是非重复的(唯一的) 从独特开始。
我正在使用asp.net应用程序中的逻辑,并且在下次刷新页面时允许显示相同的一组问题,这对我来说没问题。
答案 0 :(得分:3)
为问题实例使用List,并随机选择一个(按索引)。然后将其从列表中删除并重复。像这样的东西;
static void Main(string[] args)
{
List<string> questions = new List<string>();
for (int i = 0; i < 10; i++)
questions.Add("Question " + i);
Random r = new Random();
for (int i = 0; i < 3; i++)
{
int nextQuestion = r.Next(0, questions.Count);
Console.WriteLine(questions[nextQuestion]);
questions.RemoveAt(nextQuestion);
}
}
答案 1 :(得分:1)
其中一种方法是随机抽取元素,然后选择前三个元素。 如何在C#中进行随机播放 - Randomize a List<T> 这种方法比从大型集合的列表中删除问题更好,因为在最坏的情况下(当确定随机化或刚刚发生时),由于O(n)移除的复杂性,它可以增长到O(n ^ 2)。
答案 2 :(得分:0)
class Questions
{
const int NUMBER_OF_QUESTIONS = 10;
readonly List<string> questionsList;
private bool[] avoidQuestions; // this is the "do-not-ask-question" list
public Questions()
{
avoidQuestions = new bool[NUMBER_OF_QUESTIONS];
questionsList = new List<string>
{
"question1",
"question2",
"question3",
"question4",
"question5",
"question6",
"question7",
"question8",
"question9"
};
}
public string GetQuestion()
{
Random rnd = new Random();
int randomVal;
// get a new question if this question is on the "do not ask question" list
do
{
randomVal = rnd.Next(0, NUMBER_OF_QUESTIONS -1);
} while (avoidQuestions[randomVal]);
// do not allow this question to be selected again
avoidQuestions[randomVal] = true;
// do not allow question before this one to be selected
if (randomVal != 0)
{
avoidQuestions[randomVal - 1] = true;
}
// do not allow question after this one to be selected
if (randomVal != NUMBER_OF_QUESTIONS - 1)
{
avoidQuestions[randomVal + 1] = true;
}
return questionsList[randomVal];
}
}
只需创建Questions对象并调用questions.GetQuestions()三次