0

I want to generate non-repeated random number.
I tried the following code but it generates repeated random number.

protected void Button1_Click(object sender, EventArgs e)
    {
        Random rnd = new Random();
        int n = rnd.Next(1, 100);
        Label1.Text = n.ToString ();
    }

Edited by __avd: Added [code] tags. Encase your code in: [code] and [/code] tags.

3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by Freon22
0
int []ar={1,2,3,4,5,,...100},i,j,temp,m;
     Random rnd = new Random();
     for(m=1;m<=20;m++) {
        i = rnd.Next(1, 100);
        j = rnd.Next(1, 100);
        temp=ar[i]; ar[i]=ar[j]; ar[j]=temp;
     }
  . ...

Edited by __avd: n/a

0

Thanx adapost 4 ur attention,but pls explain this code for non-repeated random number.

1

I seen this thread a few days ago and wanted to answer it but didn't have the time. While the answer you got is very good there are other ways of doing this. One of the ways is using a generic list and generics is something that you should learn.

Make sure you call "using System.Collections.Generic;" at the top of your page.
You can see below that the first thing I did was to create the generic list from 1 to 100 or is that 99 LOL. the next thing I did was to randomly pick a number then I put that number in a label. I then removed that number from the generic list so there is no way that I can randomly pick the same number more then one time. I run the loop 50 time just to play with it. Try generic I think once you get the hang of generic you will like it.

protected void Button1_Click(object sender, EventArgs e)
    {
        List<int> myNumbers = new List<int>();
        for (int i = 1; i < 100; i++)
            {
                myNumbers.Add(i);
            }
       
        Random number = new Random();

        for (int i = 0; i < 50; i++)
            {
                int n = number.Next(0, myNumbers.Count);
                Label1.Text += "<br />" + myNumbers[n].ToString();
                myNumbers.RemoveAt(n);
            }
    }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.