Solved

Non Repeating Random Numbers

Posted on 2009-05-07
21
813 Views
Last Modified: 2012-05-06
Hi,

Could you show me where I am going wrong please?

I want to choose a number in a range between 1-10 until there are no more numbers left.

My form has a single button.

My Idea is - I create an array, populate it 1,2,3,4,5,6,7,8,910. randomly choose from the array and then remove the value that I have just chosen.

Two problems -
My page is throwing errors that al isnt declared - but it is declared in Page Load?
Will my non repeating number idea actually work? can you see any problems with it?







<%@ Page Language="VB" %>
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 

<script runat="server">
 

    

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        'get the size of the array 

        Dim myalsize As Integer = al.Count.ToString()
 

        'select a random number between 1 and size of array

        Dim RNDNUM As New Random

        Dim myrandindex As Integer = RNDNUM.Next(1, myalsize)

        'display the number which is going to be mye= index position

        Response.Write(myrandindex)

        

        'get the value from the array

        Dim myrandomvalue = al.Item(myrandindex - 1)

        

        'remove the selected random number value from the array

        al.Remove(myrandindex)

        

        'figure out how big the array is now

        myalsize = al.Count.ToString()

        'display the new array size

        Response.Write(myalsize)

        

        'display the new contents of the array

        For c = 1 To myalsize

            Response.Write(al.Item(c - 1))

        Next

        
 

    End Sub
 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        If Not Page.IsPostBack Then

            'create the array called al

            Dim al As ArrayList = New ArrayList(10)

            

            'fill the array with values 1-10

            For c = 1 To 10

                al.Add(c)

                al.TrimToSize()

                'display the contents of the array

                Response.Write(al.Item(c - 1))

            Next

        End If

        

    End Sub

</script>
 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Non Repeating Random Numbers 1 - 10 </title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Choose Random 1-10" />

    

    </div>

    </form>

</body>

</html>

Open in new window

0
Comment
Question by:Real_coffee
  • 10
  • 7
  • 3
21 Comments
 
LVL 39

Expert Comment

by:abel
ID: 24324209
You reference an object called "al", which is indeed not declared. Before we delve into your method, what is the object supposed to be and where should it come from? Mmm, I see it, it is declared inside the Page_Load, but that's another function. if you want it to be accessible by all functions, for this page, you need to add it outside the functions. This way it becomes a "member variable":

    Private al As ArrayList = New ArrayList(10)
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
       ....

you may want to choose a more recognizable name, though.
0
 
LVL 31

Expert Comment

by:Jamie McAllister MVP
ID: 24324218
Got the below example from http://www.dreamincode.net/forums/showtopic17139.htm

If you change the size of the array, and change the random number range from 49 to 10 you should be in business.
Public Class Form1

    ' Dimension the variables used in the programme

    Dim intNumber As Integer

    Dim arrNumber(0 To 5) As Integer

    Dim i, x, y As Integer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
 

        'Make sure the Label is clear

        Label1.Text = ""
 

        'We want a total of 6 Numbers (UK Lottery)
 

        For x = 0 To 5

Start:

            Randomize()

            intNumber = Int((49 * Rnd()) + 1) ' Random number 1 to 49

            For y = 0 To 5

                ' Check arrNumber (y)

                'If intnumber has already been selected, 

                'Then go and select another one.

                If intNumber = arrNumber(y) Then

                    GoTo Start

                End If

            Next y
 

            'Place the next non-repeated number in the arrNumber(x).

            arrNumber(x) = intNumber

            

        Next x

        '----------------------------------------------------

        For i = 0 To 5

            Label1.Text = Label1.Text & (arrNumber(i)) & " , "

        Next

        

    End Sub

    

End Class

Open in new window

0
 

Author Comment

by:Real_coffee
ID: 24324319
Ok Ive changed the code as you suggest (and changed the arrayname!).

Its now flipping out at line 14 with 'minValue' cannot be greater than maxValue. Parameter name: minValue

Line 14 is -  Dim myrandindex As Integer = RNDNUM.Next(1, myalsize)

So for some reason its not getting that myalsize?
<%@ Page Language="VB" %>
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitionRNDArray.dtd">
 

<script runat="server">
 

    

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        'get the size of the array 

        Dim myalsize As Integer = RNDArray.Count.ToString()
 

        'select a random number between 1 and size of array

        Dim RNDNUM As New Random

        Dim myrandindex As Integer = RNDNUM.Next(1, myalsize)

        'display the number which is going to be mye= index position

        Response.Write(myrandindex)

        

        'get the value from the array

        Dim myrandomvalue = RNDArray.Item(myrandindex - 1)

        

        'remove the selected random number value from the array

        RNDArray.Remove(myrandindex)

        

        'figure out how big the array is now

        myalsize = RNDArray.Count.ToString()

        'display the new array size

        Response.Write(myalsize)

        

        'display the new contents of the array

        For c = 1 To myalsize

            Response.Write(RNDArray.Item(c - 1))

        Next

        
 

    End Sub

    

    Private RNDArray As ArrayList = New ArrayList(10)

    

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        If Not Page.IsPostBack Then

            'create the array called al

            

            'fill the array with values 1-10

            For c = 1 To 10

                RNDArray.Add(c)

                RNDArray.TrimToSize()

                'display the contents of the array

                Response.Write(RNDArray.Item(c - 1))

            Next

        End If

        

    End Sub

</script>
 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Non Repeating Random Numbers 1 - 10 </title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Choose Random 1-10" />

    

    </div>

    </form>

</body>

</html>

Open in new window

0
 
LVL 39

Expert Comment

by:abel
ID: 24324326
I took your code and played a bit with it. This is the result for now, it shuffles the numbers a bit around:

<%@ Page Language="VB" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<script runat="server">

 

    

	Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

		Dim newArray As ArrayList = al.Clone()

		

		'select a random number between 1 and size of array

		Dim RNDNUM As New Random

		

		For i As Integer = 0 To al.Count - 1

			Dim myrandindex As Integer = RNDNUM.Next(1, newArray.Count)

			newArray(myrandindex) = al(i)

		Next
 

        

		'display the new contents of the array

		For idx = 0 To newArray.Count - 1

			Response.Write(newArray.Item(idx) & "-")

		Next

        

 

	End Sub

 

	Dim al As ArrayList = New ArrayList(10)

	Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

            

		'fill the array with values 1-10

		For idx = 0 To 9

			al.Add(idx + 1)

			If Not IsPostBack Then

				Response.Write(al.Item(idx) & "-")

			End If

		Next

        

	End Sub

</script>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Non Repeating Random Numbers 1 - 10 </title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Choose Random 1-10" />

    

    </div>

    </form>

</body>

</html>

Open in new window

0
 
LVL 39

Expert Comment

by:abel
ID: 24324330
> Its now flipping out at line 14 with 'minValue' cannot be greater than maxValue. Parameter name: minValue
yes, I've seen that error too. It is solved now.
0
 

Author Comment

by:Real_coffee
ID: 24324344
wow that was fast. Let me just check the page to see if I understand it.

back in 5 (maybe 10) mins
0
 

Author Comment

by:Real_coffee
ID: 24324530
ok.. I can see your code works but it doesnt really do what I am after.  Let me show you the output Im after (abel I might just not be understanding what you are showing me in your code) -

If you run the attached code which kind of works. you can see that i am choosing a random number and then removing it from the array. When I next press the button i want to again choose from the reduced array.

My problem is now that the array gets filled up 1-10 every time the page reloads.


<%@ Page Language="VB" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<script runat="server">

 

    

	Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim newArray As ArrayList = al.Clone()

		

		'select a random number between 1 and size of array

		Dim RNDNUM As New Random

        Dim myrandindex As Integer = RNDNUM.Next(1, al.Count)

		

        'get the value from the array based up the random index position

        Dim myrandomvalue = al.Item(myrandindex - 1)

        

        'display the selected value of the array

        Response.Write("random number =")

        Response.Write(myrandomvalue)

        Response.Write("<br />")

        

        'remove the selected random number value from the array

        al.Remove(myrandindex)

        

        

		'display the new contents of the array

        For idx = 0 To al.Count - 1

            Response.Write(al.Item(idx) & "-")

        Next

        

 

	End Sub

 

	Dim al As ArrayList = New ArrayList(10)

	Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

            

		'fill the array with values 1-10

		For idx = 0 To 9

			al.Add(idx + 1)

			If Not IsPostBack Then

				Response.Write(al.Item(idx) & " - ")

			End If

		Next

        

	End Sub

</script>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Non Repeating Random Numbers 1 - 10 </title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Choose Random 1-10" />

    

    </div>

    </form>

</body>

</html>

 

Open in new window

0
 
LVL 39

Expert Comment

by:abel
ID: 24324596
> My problem is now that the array gets filled up 1-10 every time the page reloads.

yes, that's my fault, because I had to change your code to accomodate my slightly wrong understanding of the question. In fact, this is easier. Hold on.
0
 
LVL 31

Assisted Solution

by:Jamie McAllister MVP
Jamie McAllister MVP earned 100 total points
ID: 24324603
Maybe you should consider storing the values to Viewstate or Session and only populating the full 10 values in the array if it isn't a postback?
0
 
LVL 39

Accepted Solution

by:
abel earned 150 total points
ID: 24324641
Ok, here it is. It kicks out a certain member of the arraylist. I added a session("arraylist") to store the values between the request. You'll have to add some code yourself to handle what happens at the end of the array and/or to add a refresh button to reset the array, etc.



<%@ Page Language="VB" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<script runat="server">

 

    

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim al As ArrayList = DirectCast(Session("randomarray"), ArrayList)

        

        'select a random number between 1 and size of array

        Dim RNDNUM As New Random

        

        

        Dim myrandindex As Integer = RNDNUM.Next(1, al.Count)

        al.RemoveAt(myrandindex)
 

        

        'display the new contents of the array

        For idx = 0 To al.Count - 1

            Response.Write(al.Item(idx) & "-")

        Next

        

        ' place the results back

        Session("randomarray") = al

 

    End Sub

 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        If Not IsPostBack Then

            Dim al As ArrayList = New ArrayList(10)

        

            'fill the array with values 1-10

            For idx = 0 To 9

                al.Add(idx + 1)

                Response.Write(al.Item(idx) & "-")

            Next

            Session("randomarray") = al

        End If

        

    End Sub

</script>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Non Repeating Random Numbers 1 - 10 </title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Choose Random 1-10" />

    

    </div>

    </form>

</body>

</html>

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:Real_coffee
ID: 24324761
Thats Perfect.  

I didnt even know that it was possible to store an array as a session! And here's my clumsy reset at the end of the array, attached.

Thanks for all your help  

(Thanks to you too Jamie for being interested - you were right about the session)

R_C
<%@ Page Language="VB" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<script runat="server">

 

    

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim al As ArrayList = DirectCast(Session("randomarray"), ArrayList)

        

        If al.Count = 1 Then

            'if the array is empty then fill it up with values 1-10

            For idx = 0 To 9

                al.Add(idx + 1)

                'Response.Write(al.Item(idx) & "-")

            Next

            Session("randomarray") = al

        End If

              

     

        'select a random number between 1 and size of array

        Dim RNDNUM As New Random

        

        

        Dim myrandindex As Integer = RNDNUM.Next(1, al.Count)

        Response.Write(al.Item(myrandindex))

        Response.Write("<br />")

        al.RemoveAt(myrandindex)

               

        

        'display the new contents of the array

        For idx = 0 To al.Count - 1

            Response.Write(al.Item(idx) & "-")

        Next

        

        ' place the results back

        Session("randomarray") = al

 

    End Sub

 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        If Not IsPostBack Then

            Dim al As ArrayList = New ArrayList(10)

        

            'fill the array with values 1-10

            For idx = 0 To 9

                al.Add(idx + 1)

                Response.Write(al.Item(idx) & "-")

            Next

            Session("randomarray") = al

        End If

        

    End Sub

</script>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Non Repeating Random Numbers 1 - 10 </title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Choose Random 1-10" />

    

    </div>

    </form>

</body>

</html>

 

Open in new window

0
 
LVL 39

Expert Comment

by:abel
ID: 24325009
> Neat Solution and really really quick response.

thanks for a nice compliment, always there to help :)

Btw: are you aware of the possibility of splitting points? Other experts have also giving insightful information. With splitting points you can assign an amount of the points to each of the experts.
0
 

Author Comment

by:Real_coffee
ID: 24325036
You know, I thought about that but I dont know how to split points :(
0
 
LVL 39

Expert Comment

by:abel
ID: 24325113
click the "Accept multiple solutions" link. But that's only available *before* you grade :)
0
 
LVL 39

Expert Comment

by:abel
ID: 24325122
If you still want to do that, you can send a request to the moderators by clicking "request attention" and asking for the question to be unlocked/reopened so that you can reassign points.
0
 

Author Comment

by:Real_coffee
ID: 24325160
Ok I have requested an unlock and will split fairly.
0
 
LVL 31

Expert Comment

by:Jamie McAllister MVP
ID: 24325172
Thanks for mentioning that Abel, you're a Gent.
0
 
LVL 39

Expert Comment

by:abel
ID: 24325279
You're welcome, Jamie. All in all, we are here to help fairly, so we should treat each other fairly, and help askers to find the ways to grade us well. ;-)

@Real_coffee: it may take a while until a moderator attends to the question, but normally it's somewhere within 12 hours.
0
 

Author Closing Comment

by:Real_coffee
ID: 31578944
Thanks once again.
0
 
LVL 39

Expert Comment

by:abel
ID: 24334075
lol, indeed excellent timing, WhackAMod!

actually, this brings me further away from Wizard status in this zone, and I was so close.. ;-). Tell me again, why was I doing this? :D
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now