我想知道如何在C#中实现这个任务。例如;获取N个独特的对象M集合
我收到了10个问题,其中3个要向用户显示,以 键入答案。我怎么能让程序生成3个问题, 是非重复的(独特的),假设我们以 开头的10个问题是唯一的。
我正在使用asp.net应用程序中的逻辑,并且在下次刷新页面时允许显示同一组问题,所以这对我来说不成问题。
我想知道如何在C#中实现这个任务。例如;获取N个独特的对象M集合
我收到了10个问题,其中3个要向用户显示,以 键入答案。我怎么能让程序生成3个问题, 是非重复的(独特的),假设我们以 开头的10个问题是唯一的。
我正在使用asp.net应用程序中的逻辑,并且在下次刷新页面时允许显示同一组问题,所以这对我来说不成问题。
为您的问题实例使用一个列表,并随机选择一个(按索引)。然后从列表中删除并重复。像这样的东西;
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);
}
}
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.GetQuestions()三次
其中一个方法是,随机混合元素,然后先拿他们三个。 如何在C#中洗牌 - Randomize a List<T>。
这种方法比删除大集合列表中的问题要好,因为在最坏的情况下(当随机化被确定或刚好发生时),由于O(n)移除的复杂性,它可以长到O(n^2) 。
是的,你说得对。我认为出于某种原因,使用相同的随机对象会在每次使用它时产生一个唯一的数字,但它不会。你必须在某种收藏中跟踪他们自己。 –