Search This Blog

Sunday, 21 August 2011

Random Number Generator

How to Generate 10 random numbers:


Hi, In C# programming we hav a method called Random where in code we write as follows

Random randno = new Random();

for(int i = 0; i < 10; i++)
{
         int rand = randno.Next(1,10);
         Response.Write(rand + " ");
}

for which the output will be as follows:
test output sample1:
1 7 4 8 2 8 2 4 6 1

test output sample2:
7 5 3 2 5 8 1 3 4 7


what we need is a CODE that generates only random numbers no repetitive numbers.

Hence a sample is given below to create 10 random numbers.

HTML CODE:


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Generate" OnClick="Button1_Click" />&nbsp;<br />
        <br />
        <br />
        <asp:ListBox ID="ListBox1" runat="server" Height="245px" Width="287px"></asp:ListBox></div>
    </form>
</body>
</html>

C# CODE:


 protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        GenrateUniqueNumber();
    }
    public void GenrateUniqueNumber()
    {
        int[] arr = new int[10];
        bool flag;
        for (int i = 0; i < 10; i++)
        {
            Random random = new Random();
            int randomNo = random.Next(1, 11);
            flag = true;
            for (int x = 0; x < arr.Length; x++)
            {
                if (randomNo == arr[x])
                {
                    i--;
                    flag = false;
                    break;
                }
            }
            if (flag)
                arr[i] = randomNo;
        }
        Response.Write("Set of Ten Unique Random Numbers : </br>");
        for (int z = 0; z < arr.Length; z++)
        {
            ListBox1.Items.Add((z + 1) + "-> " + arr[z].ToString());
        }
    }

Ouput :

Set 1:

 Set 2:


No comments:

Post a Comment