Kaktus12
Kaktus12

Reputation: 19

Problem with random number generator Same Numbers

I have a problem with a random number between two variables. It always gives me the same number between two numbers. Not a random numbers between two numbers.


    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Randomize()
        Dim rnd As New Random
        Dim minval As Integer
        Dim maxval As Integer

        minval = 1000 / grempamin.Value
        maxval = 1000 / grempamax.Value

        Timer1.Interval = rnd.Next(maxval, minval)

        If MouseButtons = MouseButtons.Left Then
            apimouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
            apimouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        End If
    End Sub

Upvotes: 1

Views: 172

Answers (2)

dbasnett
dbasnett

Reputation: 11773

A few changes

Private Shared rnd As New Random  '<<<<<<<<<<<<<
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    'Randomize 'not needed  '<<<<<<<<<<<<<
    Dim minval As Integer
    Dim maxval As Integer

    minval = 1000 / grempamin.Value
    maxval = 1000 / grempamax.Value
    Timer1.Interval = rnd.Next(minval, maxval + 1) '<<<<<<<<<<<<<

    If MouseButtons = MouseButtons.Left Then
        apimouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
        apimouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    End If
End Sub

Random Doc

edit: per marks comment. If there is a possibility that min and max are not min and max make this change to the rnd.next

    Timer1.Interval = rnd.Next(Math.Min(minval, maxval), Math.Max(minval, maxval) + 1) '<<<<<<<<<<<<<

Upvotes: 1

MarkL
MarkL

Reputation: 1771

If grempamin and grempamax have values that are close to each other, then dividing them into 1000 can result in the same integer value. This may be what's happening in your code.

You haven't explained your code requirements very well, but I suspect that you're making some basic math errors here.

I think grempamin and grempamax have the min and max number of seconds, so since the timer interval is in milliseconds, you'd need to multiply by 1000.

If so, then your code sample might work better as this (including dbasnett's changes):

Private rnd As New Random
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim minval As Integer
    Dim maxval As Integer

    minval = 1000 * grempamin.Value
    maxval = 1000 * grempamax.Value

    Timer1.Interval = rnd.Next(minval, maxval)

    If MouseButtons = MouseButtons.Left Then
        apimouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
        apimouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    End If
End Sub

Upvotes: 1

Related Questions