我想知道如何在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) 。
是的,你說得對。我認爲出於某種原因,使用相同的隨機對象會在每次使用它時產生一個唯一的數字,但它不會。你必須在某種收藏中跟蹤他們自己。 –