Solved

Non Repeating Random Numbers

Posted on 2009-05-07
21
819 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 32

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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
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 32

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
 

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 32

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

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
This video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…

691 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