Non-repetitive random number in asp.net C#
Solution 1
You can put the numbers in a list, and generate your random number not based on your real numbers, but on the remaining items in the list.
Random random = new Random();
List<int> nums = new {1, 2, 3, 4, 5, 6}; // or whatever you need to put there.
List<int> result = new List<int>(); // will hold your results in order.
while(nums.Count > 0){
int idx = random.next(0, nums.Count);
result.add(nums[idx]);
nums.RemoveAt(idx);
}
return result;
You don't have to use int
values in your nums
list; it can be your Question
objects, or whatever you need; What you will get is the items in a random order.
Solution 2
You need a list of Panels/Indices and then shuffle them with for example Fisher-Yates .
Solution 3
Start with a list of all your panel numbers:
var panels = new List<int>() { 1, 2, 3, 4, 5, 6 }
You will need to "remember" what panels you have already seen accross postbacks, so you could store this in ViewState
or Session
maybe.
Each time you need a new number:
Random random = new Random();
var idx = random.next(0, panels.Count);
var selectedPanel = panels[idx];
panels.Remove(selectedPanel);
When panels.Count() == 0
, re-inistialise it with all the numbers.
Mostafa
Interested in ASP.NET MVC and C# Development , Trying to do his best by inspiring of proven architectures , best practices and design pattern. New to Java and Client-side development He is a BIG fan of Real Madrid , too.
Updated on June 04, 2022Comments
-
Mostafa almost 2 years
I have 6 question in 6 asp.net panel server control , I need to show them all panel one by one in random order( one question is visible and other invisible every time ).
I don't know how to exclude the number from generating again . I write like this :
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Random rnd = new Random(); int startNumber = rnd.Next(1, 6); ShowNextPanel(startNumber); } } private void ShowNextPanel(int excludeNumber) { Random rnd = new Random(); //I need to exclude the "excludeNumber" here but I don't know how !? int number = rnd.Next(1, 6); switch (number) { case 1: { Panel1.Visible = true; break; } case 2: { Panel2.Visible = true; break; } case 3: { Panel3.Visible = true; break; } case 4: { Panel4.Visible = true; break; } case 5: { Panel5.Visible = true; break; } case 6: { Panel6.Visible = true; break; } } } protected void Button1_Click(object sender, EventArgs e) { // InsertToDB(1, DropDownList1.SelectedValue); Panel1.Visible = false; ShowNextPanel(1); } protected void Button2_Click(object sender, EventArgs e) { // InsertToDB(2, DropDownList2.SelectedValue); Panel2.Visible = false; ShowNextPanel(2); } //and go on till button6_click