Results 1 to 35 of 35

Thread: Random Number Generator - Store generated numbers

Hybrid View

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Random Number Generator - Store generated numbers

    Right so my generator is working, but I now want to take the numbers that it generates and add them to a list of generated numbers. So you can monitor what numbers have been generated.

    Then ideally a way to exclude these numbers from being generated again.

    Heres my code for my generate button

    vb Code:
    1. Dim Low As Integer = 1
    2.         Dim High As Integer
    3.         High = HighNum.Text
    4.         Low = TextBox2.Text
    5.         Get_Random(Low, High)
    6.         TextBox1.Visible = True
    7.         Beep()


    And my Random Number code
    vb Code:
    1. Sub Get_Random(ByVal Low As Integer, ByVal High As Integer)
    2.  
    3.         TextBox1.Text = Math.Floor((High - Low + 1) * Rnd() + Low)
    4.  
    5.     End Sub

    Can I then somehow work in a, if number is in listbox regenerate?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Random Number Generator - Store generated numbers

    You have basically three options:

    1. Generate the whole list first, generate random numbers and remove those from the list as you go.

    2. Generate the whole list first, order it randomly and then use the items sequentially.

    3. Generate random numbers and add the corresponding items to a list. Each time you generate a number, check whether it's in the list of those already used and discard it if it is.

    Option 1 is the best choice if you need to make a large number of random selections without using all items. Option 2 is best if you will use every item. Option 3 is OK if you will only use a small number of items.

    For examples of options 1 and 2, follow the CodeBank link in my signature and search for the word "random" in the thread titles. You'll find two that apply.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    Alright so I am going to attempt to use your code "Unique, Random Selections from a List" and try and change it a bit to suit my needs. So far I added my code just to the start to allow user input values.

    vb Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.         Dim list As New ArrayList
    3.  
    4.         Dim Low As Integer = 1
    5.         Dim High As Integer
    6.         High = TextBox1.Text
    7.         Low = TextBox2.Text
    8.  
    9.         For i As Integer = Low To High
    10.             'Add the numbers to the collection.
    11.             list.Add(i)
    12.         Next i
    13.  
    14.         Dim rand As New Random
    15.         Dim index As Integer
    16.         Dim item As Object
    17.  
    18.         'Display the items in random order.
    19.         While list.Count > 0
    20.             'Choose a random index.
    21.             index = rand.Next(0, list.Count)
    22.  
    23.             'Get the item at that index.
    24.             item = list(index)
    25.  
    26.             'Remove the item so that it cannot be chosen again.
    27.             list.RemoveAt(index)
    28.  
    29.             'Display the item.
    30.             MessageBox.Show(item.ToString())
    31.         End While
    32.     End Sub

    From here once I click the generate button it generates random numbers into a message box, but will generate all x amount depending on the input values. I need to be able to change this to only generate once, once the button is pressed. And also for the results to be shown in either a text box or label so that I can work in my multiforms.



    vb Code:
    1. MessageBox.Show(item.ToString())

    Now I have tried changing this value to the following but I cannot get it to work without errors. The errors being with (item.ToString()).

    Am I just not using this the proper way?

    vb Code:
    1. TextBox1.Text(item.ToString())
    2. TextBox1.Show(item.ToString())

    And for the removing from the list, is it possible to change this to add it to a listbox of generated numbers aswell as removing it from the list so it wont be regenerated?
    vb Code:
    1. list.RemoveAt(index)

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    I have now changed the output to suit my multiform layout. This is what I used to get it to work.

    vb Code:
    1. TextBox3.Text = item.ToString


    The only real thing left to do is to incorporate the listbox to show these generated numbers. Also I have noticed that it still will generate numbers that have been done before. If I set the low and high to say 10 - 20 it will generate the same numbers twice a few times when ther are still un generated numbers sitting there.

    Maybe this is to do with how I am letting the user input these numbers?
    Last edited by Noob script kiddie; Nov 24th, 2010 at 05:23 PM.

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    I hope you come back soon

    I have added the following code to the generate button and it sends the generated numbers to the listbox.

    vb Code:
    1. ListBox1.Items.Add(TextBox3.Text)
    Last edited by Noob script kiddie; Nov 24th, 2010 at 06:01 PM. Reason: Changed some things since posting

  6. #6
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Random Number Generator - Store generated numbers

    Some implementation notes:

    Quote Originally Posted by jmcilhinney View Post
    1. Generate the whole list first, generate random numbers and remove those from the list as you go.
    Since you will be doing index-based access on the collection, use an array rather than a List. To perform removing when dealing with an array, simply consider a subset of the array each time. That is, keep a track of how many items you have left to return. On each iteration, generate a random integer from 0 (inclusive) to number of items left to return (exclusive). Use that as the index of the element to return this iteration, then overwrite its value with the value of the last element you are currently considering. Next time through, you consider the range of the array without that last element.

    It would end up looking something like this as an example run: (Bold elements are the range of the array we are interested in each iteration, Red element is the element that was overwritten at the end of the previous iteration)
    Code:
      Array:              |  #  |     |
      0 1 2 3 4 5 6 7 8 9 | Rem | Rnd | Returned
     ---------------------+-----+-----+----------
      0 1 2 3 4 5 6 7 8 9 | 10  |  3  | 3
      0 1 2 9 4 5 6 7 8 9 |  9  |  0  | 0
      8 1 2 9 4 5 6 7 8 9 |  8  |  7  | 7
      8 1 2 9 4 5 6 7 8 9 |  7  |  1  | 1
      8 6 2 9 4 5 6 7 8 9 |  6  |  4  | 4
      8 6 2 9 5 5 6 7 8 9 |  5  |  1  | 6
      8 5 2 9 5 5 6 7 8 9 |  4  |  0  | 8
      9 5 2 9 5 5 6 7 8 9 |  3  |  1  | 5
      9 2 2 9 5 5 6 7 8 9 |  2  |  1  | 2
      9 2 2 9 5 5 6 7 8 9 |  1  |  0  | 9
    Quote Originally Posted by jmcilhinney View Post
    2. Generate the whole list first, order it randomly and then use the items sequentially.
    This is not actually any better in terms of performance than the first option in the case where you select the whole list, if you code the first option correctly. You need to be careful that you do not introduce a sampling bias (i.e. some orders are more likely to occur than other orders). This can be the most easily implemented, however.

    Quote Originally Posted by jmcilhinney View Post
    3. Generate random numbers and add the corresponding items to a list. Each time you generate a number, check whether it's in the list of those already used and discard it if it is.
    Use a HashSet for this, not a List. The check as to whether it is in the list will be constant time, rather than increasing linearly with List size.
    Last edited by Evil_Giraffe; Dec 6th, 2010 at 09:10 PM.

  7. #7
    I don't do your homework! opus's Avatar
    Join Date
    Jun 2000
    Location
    Good Old Europe
    Posts
    3,863

    Re: Random Number Generator - Store generated numbers

    By using the code to populate the "list" inside the Sub Button1_Click you regenerate this list each time you click that button. You need to declare the list in the general area in order to keep it after the Button1_Click has been run and to be able to use it on the next click.
    You're welcome to rate this post!
    If your problem is solved, please use the Mark thread as resolved button


    Wait, I'm too old to hurry!

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    Alright so I thought I had it working, but turns out I don't.

    I read what Opus wrote, and from what I can understand I would need to move the creating of the list to somewhere other than the button. I tried this by moving the following to the form1 load sub:

    vb Code:
    1. Dim Low As Integer = 1
    2.         Dim High As Integer
    3.         High = TextBox1.Text
    4.         Low = TextBox2.Text
    5.  
    6.         For i As Integer = Low To High
    7.             'Add the numbers to the collection.
    8.             list.Add(i)
    9.         Next i

    This causes more problems, so where exactly should I move it/should I even be moving it at all.
    Last edited by Noob script kiddie; Nov 28th, 2010 at 09:24 PM.

  9. #9
    I don't do your homework! opus's Avatar
    Join Date
    Jun 2000
    Location
    Good Old Europe
    Posts
    3,863

    Re: Random Number Generator - Store generated numbers

    What kind of "more Problems" do you get?
    Without seeing all your code, we can't tell.
    BTW: You are mioxing up Strings and number-type variables(High get the text[i.e. String] from a textbox, but it is used as if it is an Integer [for i as integer = Low to High])
    You're welcome to rate this post!
    If your problem is solved, please use the Mark thread as resolved button


    Wait, I'm too old to hurry!

  10. #10

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    Here is my entire code for form1. At the moment, it generates a new list every time I click generate.

    vb Code:
    1. Friend Module Module1
    2.     Friend F1 As Form1
    3.     Friend F2 As Form2
    4. End Module
    5.  
    6. Public Class Form1
    7.     Private Declare Sub keybd_event Lib "user32" _
    8.                                (ByVal bVk As Byte, _
    9.                                 ByVal bScan As Byte, _
    10.                                 ByVal dwFlags As Byte, _
    11.                                 ByVal dwExtraInfo As Byte)
    12.     Private Const VK_CONTROL As Byte = &H11
    13.     Private Const VK_8 As Byte = &H38
    14.     Private Const KEYEVENTF_KEYDOWN As Byte = &H0
    15.     Private Const KEYEVENTF_KEYUP As Byte = &H2
    16.     Dim list As New ArrayList
    17.  
    18.  
    19.  
    20.     Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
    21.         'low Number
    22.     End Sub
    23.  
    24.     Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    25.         'High Number
    26.     End Sub
    27.  
    28.     Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
    29.         'Generated Number
    30.  
    31.         If F2 Is Nothing Then
    32.             F2 = New Form2()
    33.             F2.Show()
    34.  
    35.         Else
    36.             F2.TextBox1.Text = TextBox3.Text
    37.         End If
    38.     End Sub
    39.  
    40.     Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    41.         'Listbox
    42.     End Sub
    43.  
    44.    
    45.  
    46.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    47.  
    48.         Dim Low As Integer = 1
    49.         Dim High As Integer
    50.         High = TextBox1.Text
    51.         Low = TextBox2.Text
    52.  
    53.         For i As Integer = Low To High
    54.             'Add the numbers to the collection.
    55.             list.Add(i)
    56.         Next i
    57.         Dim rand As New Random
    58.         Dim index As Integer
    59.         Dim item As Object
    60.  
    61.         'Display the items in random order.
    62.         'While list.Count > 0
    63.         'Choose a random index.
    64.         index = rand.Next(0, list.Count)
    65.  
    66.         'Get the item at that index.
    67.         item = list(index)
    68.  
    69.         'Remove the item so that it cannot be chosen again.
    70.         list.RemoveAt(index)
    71.  
    72.         'Display the item.
    73.         TextBox3.Text = item.ToString
    74.         ListBox1.Items.Add(TextBox3.Text)
    75.         'End While
    76.         Form3.Close()
    77.         Form3.Show()
    78.         tmrWait.Interval = 5000
    79.         tmrWait.Start()
    80.  
    81.  
    82.     End Sub
    83.  
    84.  
    85.  
    86.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    87.  
    88.  
    89.  
    90.         Dim tmrWait As New Timer
    91.  
    92.         F1 = Me
    93.  
    94.         If F2 Is Nothing Then
    95.             F2 = New Form2()
    96.             F2.Show()
    97.  
    98.         End If
    99.     End Sub
    100.  
    101.     Private Sub TextBox4_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox4.TextChanged
    102.         'Enter your own title
    103.  
    104.         If F2 Is Nothing Then
    105.             F2 = New Form2()
    106.             F2.Show()
    107.  
    108.         Else
    109.             F2.TextBox2.Text = TextBox4.Text
    110.         End If
    111.     End Sub
    112.  
    113.  
    114.  
    115.     Private Sub tmrWait_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrWait.Tick
    116.         Form3.Close()
    117.         tmrWait.Stop()
    118.     End Sub
    119.  
    120.     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    121.         keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYDOWN, 0)
    122.         keybd_event(VK_8, 0, KEYEVENTF_KEYDOWN, 0)
    123.         keybd_event(VK_8, 0, KEYEVENTF_KEYUP, 0)
    124.         keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0)
    125.  
    126.         Me.Close()
    127.     End Sub
    128.  
    129.     Private Sub TextBox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    130.  
    131.     End Sub
    132. End Class

    If you look at my button_1 you can see that I have disabled the lines

    vb Code:
    1. While list.Count > 0d
    2. End While

    If I allow these, the generated list will generate all numbers (depending on values) to the listbox. So say I enter 10-20 in the low and high boxes, it would display all 11 possible values in the listbox box.

    Disabling it like I have done, it seems to generate 1 number to the listbox. However then you get double ups. So maybe this could be where its going wrong?

  11. #11
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Random Number Generator - Store generated numbers

    You'll want to have a way to generate a new list of numbers outside of your button click. In the small example here I chose the .Leave event for the TextBoxes to create a new list. Whatever you do you'll want more error checking (is highValue > lowValue etc.)

    Code:
    Public Class Form1
    
        Dim numbers As List(Of Integer)
    
        Private Sub TextBox_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) _
            Handles lowValueTextBox.Leave, highValueTextBox.Leave
    
            If Integer.TryParse(lowValueTextBox.Text, Nothing) AndAlso Integer.TryParse(highValueTextBox.Text, Nothing) Then
                numbers = Enumerable.Range(CInt(lowValueTextBox.Text), CInt(highValueTextBox.Text) - CInt(lowValueTextBox.Text) + 1).ToList
                GeneratedNumbersListBox.Items.Clear()
            End If
    
        End Sub
    
        Private Sub GenerateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
            Handles GenerateButton.Click
    
            If numbers.Count > 0 Then
                Dim rnd As New Random
                Dim idx As Integer = rnd.Next(0, numbers.Count)
                GeneratedNumbersListBox.Items.Add(numbers.Item(idx))
                numbers.RemoveAt(idx)
            Else
                MessageBox.Show("No more numbers to choose from the range")
            End If
    
        End Sub
    End Class

  12. #12

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    Alright, I'll give this a go now and see what I can get to work..

    Cheers
    Last edited by Noob script kiddie; Nov 29th, 2010 at 05:35 PM.

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    That seems to be working fine. Couple of things though, I need to get the latest generated number to appear in a box that will display the number on the control screen. I used to get it to work by using,
    vb Code:
    1. TextBox3.Text = item.ToString

    However this causes the error Object reference not set to an instance of an object.

    Have you got any suggestions?

  14. #14
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Random Number Generator - Store generated numbers

    I'll need a little more context than that 1 line to answer that. Mind posting the rest of your code so I can take a look?

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    Well this used to be my generate button:

    vb Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.  
    3.         Dim Low As Integer = 1
    4.         Dim High As Integer
    5.         High = TextBox1.Text
    6.         Low = TextBox2.Text
    7.  
    8.         For i As Integer = Low To High
    9.             'Add the numbers to the collection.
    10.             list.Add(i)
    11.         Next i
    12.         Dim rand As New Random
    13.         Dim index As Integer
    14.         Dim item As Object
    15.  
    16.         'Display the items in random order.
    17.         'While list.Count > 0
    18.         'Choose a random index.
    19.         index = rand.Next(0, list.Count)
    20.  
    21.         'Get the item at that index.
    22.         item = list(index)
    23.  
    24.         'Remove the item so that it cannot be chosen again.
    25.         list.RemoveAt(index)
    26.  
    27.         'Display the item.
    28.         TextBox3.Text = item.ToString
    29.         ListBox1.Items.Add(TextBox3.Text)
    30.         'End While
    31.         Form3.Close()
    32.         Form3.Show()
    33.         tmrWait.Interval = 5000
    34.         tmrWait.Start()
    35.  
    36.  
    37.     End Sub

    And more specifically these two lines:
    vb Code:
    1. TextBox3.Text = item.ToString
    2.         ListBox1.Items.Add(TextBox3.Text)

    This would then put the generated number in the listbox and textbox. The reason I need it in both is that I duplicate the text from the textbox and copy it to another form that is my display screen.

    That help a bit more?

  16. #16
    I don't do your homework! opus's Avatar
    Join Date
    Jun 2000
    Location
    Good Old Europe
    Posts
    3,863

    Re: Random Number Generator - Store generated numbers

    As long as you are only copying new lines of code into your old (copied?) code, the problems will persist!
    As MattP (Post#10) and I(Post#6) have stated you need to run the code to generate the list only once! since you are doing that each time you click your Button1 it won't change!
    Remember your list holding all the numbers is alled "list", why are you using a new one called "ListBox1" now?
    You're welcome to rate this post!
    If your problem is solved, please use the Mark thread as resolved button


    Wait, I'm too old to hurry!

  17. #17
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Random Number Generator - Store generated numbers

    you are getting all messed up

    why don't you atsrt again and apply what you are being told in you own way rather that altering code you don't understand?

    my penneth...

    make a setup button and a get random button

    enter you mins and maxes

    create an array to hold the random values

    pressing setup will fill the array and then using a pair of random numbers equal to the size of the array

    use the option no 3 given to you by the first respondant to swap the contents of the array around
    this gives you your randomness

    now simple read off the array when the get random is pressed keeping a count of where you are in the array.

    reporting the value from the array in the output text box as required

    all seems simple to us but we have been doing this for 35 years or so!

  18. #18
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Random Number Generator - Store generated numbers

    Code:
    Public Class Form1
    
        Dim foo As CommonRandomQ
    
        Private Sub Button1_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) Handles Button1.Click
            'creation
            Dim lo, hi As Integer
            Dim err As Boolean = False
            'validate user input
            If Not Integer.TryParse(TextBox1.Text, lo) Then
                err = True 'not a number
            End If
            If Not Integer.TryParse(TextBox2.Text, hi) Then
                err = True 'not a number
            End If
    
            If Not err Then
                foo = New CommonRandomQ(Math.Min(lo, hi), Math.Max(lo, hi))
                ListBox2.Items.Clear()
                lb1Upd()
                Label1.Text = String.Format("Generated {0} numbers.", foo.CountRemaining.ToString("n0"))
            Else
                Label1.Text = "Only numbers"
            End If
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) Handles Button2.Click
            'pick one
            If foo.CountRemaining > 0 Then ListBox2.Items.Add(foo.NextRandom)
            lb1Upd()
            Label1.Text = String.Format("{0} number(s) remain.", foo.CountRemaining.ToString("n0"))
        End Sub
    
        Private Sub Button3_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) Handles Button3.Click
            'start over using the same list
            foo.Restart()
            lb1Upd()
            ListBox2.Items.Clear()
        End Sub
    
        Private Sub lb1Upd()
            'update not selected listbox
            ListBox1.Items.Clear()
            ListBox1.Items.AddRange(foo.ListNotSelected.ToArray)
        End Sub
    
        Private Sub Form1_Shown(ByVal sender As Object, _
                                ByVal e As System.EventArgs) Handles Me.Shown
            TextBox1.Text = "10"
            TextBox2.Text = "1"
        End Sub
    End Class
    
    Class CommonRandomQ
        Private Shared _prng As New Random
        Private _list As List(Of String)
        Private _working As List(Of String)
    
        Public Sub New(ByVal High As Integer) '0-high inclusive
            Me.New(0, High)
        End Sub
    
        Public Sub New(ByVal Low As Integer, ByVal High As Integer) 'low-high inclusive
            Me._list = New List(Of String)
            For x As Integer = Low To High
                Me._list.Add(x.ToString)
            Next
            Me.Restart()
        End Sub
    
        Public Sub Restart() 're-use same original list
            Me._working = New List(Of String)
            Me._working.AddRange(Me._list)
        End Sub
    
        Public Function ListNotSelected() As List(Of String)
            Return Me._working
        End Function
    
        Public Function NextRandom() As String
            Dim rv As String = Nothing
            If Me._working.Count > 0 Then
                Dim idx As Integer = _prng.Next(0, Me._working.Count)
                rv = Me._working(idx)
                Me._working.RemoveAt(idx)
            End If
            Return rv
        End Function
    
        Public ReadOnly Property CountRemaining() As Integer
            Get
                Return Me._working.Count
            End Get
        End Property
    End Class
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  19. #19

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    I understand what you guys are saying but its working now! All I need to do is get the output to the textbox and its complete.. So why would I want to start again?

    Its generating a random number between user inputted values, its not generating a new list every time and its storing the generated numbers in the listbox.

    All I now need is for the latest generated number to be placed into the Textbox3 on my form1!

  20. #20

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    Ok so I fumbled my way to getting it working. I just swapped the order I was trying to do things and that seemed to work.

    I was trying to go generate to listbox, then display in textbox.
    The proper way was generate to textbox, and then add to listbox.

    vb Code:
    1. If numbers.Count > 0 Then
    2.             Dim rnd As New Random
    3.             Dim idx As Integer = rnd.Next(0, numbers.Count)
    4.             'ListBox1.Items.Add(numbers.Item(idx))
    5.             TextBox3.Text = (numbers.Item(idx))
    6.             numbers.RemoveAt(idx)
    7.             ListBox1.Items.Add(TextBox3.Text)
    8.         Else
    9.             MessageBox.Show("There are no more numbers left to generate!")
    10.         End If
    11.  
    12.         Form3.Show()
    13.         tmrWait.Interval = 5000
    14.         tmrWait.Start()

    Everything all go, I guess the real last thing to do is to safe it all up.

    When no numbers are entered and they press generate it will crash kinda thing. No ideas on that?

  21. #21

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    Added this as a start.. Surprised it worked first Pop

    vb Code:
    1. If TextBox2.Text > TextBox1.Text Then
    2. MessageBox.Show("Your high value is lower than your low value!")
    3. Else

    Question about that is, should I do it that way you have the message box appear in the else part?

    Also added these. Now I am adding all of this to my generate button. Should this be placed here or is there a secrete sub you could put it in, and I guess call it later.

    vb Code:
    1. If TextBox1.Text = Nothing Then
    2.             MessageBox.Show("Please enter a High Value!")
    3.         Else
    4.             If TextBox2.Text = Nothing Then
    5.                 MessageBox.Show("Please enter a Low Value!")
    6.             Else
    Last edited by Noob script kiddie; Nov 30th, 2010 at 04:09 PM.

  22. #22
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Random Number Generator - Store generated numbers

    Quote Originally Posted by Noob script kiddie View Post
    Added this as a start.. Surprised it worked first Pop

    vb Code:
    1. If TextBox2.Text > TextBox1.Text Then
    2. MessageBox.Show("Your high value is lower than your low value!")
    3. Else

    Question about that is, should I do it that way you have the message box appear in the else part?
    If you look at some of the other examples, you will see the correct way to handle the conversion from text to numbers. Your comparison may appear to work but it isn't how it should be done.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  23. #23
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Random Number Generator - Store generated numbers

    at this point he has not tested for alpha inputs so his test will work fine numbers as literals or some kind of numeric datatype all test the same in textboxes

    the empty and alphabetic tests should prehaps happen before the simplistic text1.text>text2.text expressions though for completness

    the kids getting there though...

    but it is always good to restart your solution as you are able to utilise new concepts that make for a more robust and/or faster solution, sometimes even prettier and smaller/easier to read.

    "programming is more of an art than a science"

  24. #24

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    You guys get me worried when you talk about me

    What are Alpha inputs?
    What is conversion from text to numbers? I don't understand what your referring to..

  25. #25
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Random Number Generator - Store generated numbers

    Quote Originally Posted by incidentals View Post
    at this point he has not tested for alpha inputs so his test will work fine numbers as literals or some kind of numeric datatype all test the same in textboxes

    the empty and alphabetic tests should prehaps happen before the simplistic text1.text>text2.text expressions though for completness

    the kids getting there though...

    but it is always good to restart your solution as you are able to utilise new concepts that make for a more robust and/or faster solution, sometimes even prettier and smaller/easier to read.

    "programming is more of an art than a science"
    If you are saying that as long as the user inputs only numbers the code will work, then yes. We all know that users never make mistakes

    @noob - look at the code I posted. TryParse is something you should search for here http://msdn.microsoft.com/en-us/libr...VS.100%29.aspx.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  26. #26

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    Quote Originally Posted by dbasnett View Post
    If you are saying that as long as the user inputs only numbers the code will work, then yes. We all know that users never make mistakes

    @noob - look at the code I posted. TryParse is something you should search for here http://msdn.microsoft.com/en-us/libr...VS.100%29.aspx.
    Thanks, I looked at this code before but didn't want to start again. However I got to work this morning and just figured why not.. Set it up and its much nicer. I have incorporated my side of things to it and its working well. I like the fact that it picks up on non alphanumeric (thanks incidentals)

    Hope your happy with me using it

    The only problem now I'm having is with the timer I'm using, however that is a different thread so I will take that there.
    http://www.vbforums.com/showthread.php?t=633869

  27. #27
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: Random Number Generator - Store generated numbers

    we like to test everything

    alpha - alphabetic/alphanumeric a mix of letters and numbers and spaces and stuff

    we like to findout what breaks our programs and then prevent it

  28. #28

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    141

    Re: Random Number Generator - Store generated numbers

    Another question, is there a way to have a button that removes a selected item in the Generated list from the virtual list of numbers? So they could effectively delete certain numbers from being generated?

  29. #29
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Random Number Generator - Store generated numbers

    Quote Originally Posted by Noob script kiddie View Post
    Another question, is there a way to have a button that removes a selected item in the Generated list from the virtual list of numbers? So they could effectively delete certain numbers from being generated?
    Most of the implementations start by generating a collection of the items to return by doing Enumerable.Range(0, numberOfItems).ToList (or .ToArray)

    The Enumerable.Range() method will return a sequence of increasing integers. The ToX() method collapses that sequence into the collection. So simply replacing that with a collection that just contains the elements you want returned will do what you want.

  30. #30
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Random Number Generator - Store generated numbers

    This topic has just been covered on the Visual Basic site of About.com whic hare linked to from the VB News box at the top of the forum.

    The link you'd be wanting is Collections of Random Integers - Redux

  31. #31
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Random Number Generator - Store generated numbers

    @evil - The implementation of a specific method always depends on the specifics, and balancing performance with maintainability.

    If the task is to simulate one of the popular lottery games and display the results to the user then using a list is probably best. If the task is to simulate 10,000,000 draws and track the results, then a list might not be the best approach.

    What do you do if the task is to pick random integers(without repeats) from {-17179869184 to 17179869184} inclusive? I don't think list or arrays will work out well, do you?
    Last edited by dbasnett; Dec 8th, 2010 at 07:22 AM.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  32. #32
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Random Number Generator - Store generated numbers

    Quote Originally Posted by dbasnett View Post
    What do you do if the task is to pick random integers(without repeats) from {-17,179,869,184 , 17,179,869,184}? I don't think list or arrays will work out well, do you?
    Seems to work okay to me, maybe I'm misunderstanding you:

    Code:
      Array:                          |  #  |     |
       0   1   2   3   4   5   6   7  | Rem | Rnd | Returned
     ---------------------------------+-----+-----+----------
      -17 179 869 184  17 179 869 184 |  8  |  6  | 869
      -17 179 869 184  17 179 184 184 |  7  |  6  | 184
      -17 179 869 184  17 179 184 184 |  6  |  0  | -17
      179 179 869 184  17 179 184 184 |  5  |  3  | 184
      179 179 869  17  17 179 184 184 |  4  |  3  |  17
      179 179 869  17  17 179 184 184 |  3  |  0  | 179
      869 179 869  17  17 179 184 184 |  2  |  0  | 869
      179 179 869  17  17 179 184 184 |  1  |  0  | 179
    I'm assuming that "without repeats" recognises the doubled up elements as two separate elements? If you meant that it should only return one of those elements, then you simply make sure your source set doesn't contain duplicates, which is a trivial extension, or you pick option 3. Neither implementation of option 1 would handle that question without modification. But as I wasn't suggesting option 1 over option 3, I'm not sure what your point is in bringing that up?


    As to balancing performance and maintainability, *shrug* in this instance we're not talking about massive amounts of time either way, although a rough performance measure puts the Array method at over twice as fast as the List method.
    But the array is the natural data structure for the operations we're performing in algorithm 1, namely index based access. The List can do it, of course, and allows for using the RemoveAt method to let the code speak more clearly, but given that we should be encapsulating the Randomise inside it's own method (and also, for my money, class) then we're talking about 5 lines of code, inside a low level method, I don't value that additional immediate clarity overly. It really doesn't take long to grasp what the array method is doing when it stands on its own.

    Plus, if you want ultra maintainable code, without worrying particularly about performance, you should be using option 2.


    With the difference between the List and HashSet in algorithm 3, this really is important, and doesn't change the readability of the algorithm at all (you'd only change the declaration of the instance, I believe the methods you'd use are all named the same, from memory)


    So, no, I don't believe my advice is particularly context specific, as I was just giving some additional advice on the implementation of each of the algorithms, not suggesting a particular one over the other. I was assuming the correct approach had been picked for the OP's scenario and offering some additional insight into that approach.

  33. #33
    I don't do your homework! opus's Avatar
    Join Date
    Jun 2000
    Location
    Good Old Europe
    Posts
    3,863

    Re: Random Number Generator - Store generated numbers

    [QUOTE=dbasnett;3923815{-17,179,869,184 , 17,179,869,184[/QUOTE]
    was meant to be -17 179 869 184 up to 17 179 869 184 .
    dbasnett used to "," to seperate thousands, millions etc.
    You're welcome to rate this post!
    If your problem is solved, please use the Mark thread as resolved button


    Wait, I'm too old to hurry!

  34. #34
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Random Number Generator - Store generated numbers

    Ooooooh, d'oh that makes sense as a question now

    However, it's a rather extreme scenario when we're talking about going outside the capacity of the built-in collection classes. In other words, if you were faced with that scenario you would look at the three options suggested by jmcilhinney, see that none of them were good enough for your scenario, and go on to write some specialised classes that allowed you to virtualise the range on Int64s and take out portions of it without ever having to hold the entire range explicitly in memory.

    That would be a fun challenge to do, actually. Maybe later

  35. #35
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Random Number Generator - Store generated numbers

    Quote Originally Posted by opus View Post
    was meant to be -17 179 869 184 up to 17 179 869 184 .
    dbasnett used to "," to seperate thousands, millions etc.
    I fixed the post in place.

    @evil - my point was that you pick the tool that best fits the job.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width