Need some help.

I have this random number generator, that will generate 6 random number, but I don't know why some times it display only 4, 3, or 2 number. here is my code. I'm using VB .NET


    Public Function numGenerate(times As Integer) As Integer
        Dim rnd As New Random
        Dim pass As Integer
        Dim counter As Integer

        Do Until counter >= times
            pass = pass & (rnd.Next(0, 9))
            counter += 1
        Loop
        Return pass
    End Function
EnniobozzettiAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brian CroweDatabase AdministratorCommented:
is pass supposed to be an integer or a string?  Except for that it appears as though you are trying to create a random number with [times] digits
0
S-TwilleyCommented:
I think BriCrowe is right....  the & operator is used to concatenate values (i.e. join them together)... but since pass is declared as an integer, the joint expression after using & is converted back to an integer... so any trailing zeros are lost.

For instance:

If 3 was passed to your method... and the generated numbers were 4,9 and 2

                                  string
                                 returned            converted
                                   after                     to
                             concatenation           integer
1st iteration:
pass =          0 & 4   ->  "04"                  -> 4

2nd iteration:
pass =          4 & 9   ->  "49"                 -> 49

3rd iteration:
pass =         49 & 2   ->  "492"                -> 492

Integer Value 492 is returned

=======================

Say you passed 4 this time, and the numbers returned were 0,0,0 and 3

                                  string
                                 returned            converted
                                   after                     to
                             concatenation           integer
1st iteration:
pass =          0 & 0   ->  "00"                  -> 0

2nd iteration:
pass =          0 & 0   ->  "00"                 -> 0

3rd iteration:
pass =         0 & 0   ->  "00"                  -> 0

4th iteration:
pass =         0 & 2   ->  "02"              ->     2


Integer value 2  is returned.

===================

If you explain a bit more about what you're after... then we could help, do you want the leading zero's ?
0
Mike TomlinsonMiddle School Assistant TeacherCommented:
The following will generate a number with the specified length:

    Public Function numGenerate(ByVal length As Integer) As Integer
        Dim i As Integer
        Dim rnd As New Random
        Dim min As Integer
        Dim number As String

        For i = 1 To length
            If i = 1 Then
                min = 1
            Else
                min = 0
            End If
            number = number & (rnd.Next(min, 10))
        Next

        Return Integer.Parse(number)
    End Function

Note that the second parameter to Next() should be 10, not 9.
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

LacutahCommented:
The random number generator in Visual Basic must be "Randomized" to provide true(r) random numbers.  The reason behind this is that for testing purposes, you would want to see the same series of numbers repeated every time the application is run.

To Randomize, use the "Randomize" visual basic method.

Randomize is over-ridden.  Call:
    Randomize()
with no arguments, and it will use the system timer value as a seed.
Call:
   Randomize(number as object)
to use the obect (number or any object) as the "seed" for the random number generator.

<plagerized from SDK> Note   To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.
0
Mike TomlinsonMiddle School Assistant TeacherCommented:
You don't need to call the Randomize() method when using the Random() class.  You only need Randomize() if you are using the Rnd() function (which is a carryover from VB6 and resides in the Microsoft.VisualBasic namspace).  In this case we made a bad choice by naming our instance of the Random() class "rnd" making it confusing.  To make it clearer we should probably use a different name:

    Public Function numGenerate(ByVal length As Integer) As Integer
        Dim i As Integer
        Dim r As New Random
        Dim min As Integer
        Dim number As String

        For i = 1 To length
            If i = 1 Then
                min = 1
            Else
                min = 0
            End If
            number = number & (r.Next(min, 10))
        Next

        Return Integer.Parse(number)
    End Function

"The default constructor initializes a new instance of the Random class, using a time-dependent default seed value."
0
S-TwilleyCommented:
Idle... if your function is what they're after (I was a little unsure to be honest)... then the return values for differing lengths would be:

Length = 1:   1  to  9    (should this not really be 0 - 9)
Length = 2:   10 to 99
Length = 3:   100 to 999
Length = 4:   1000 to 9999

I think the implementation  for length=1 needs to be reworked as a special case... but where length is greater than or equal 2... I feel that the return values are like this (:

Length = 2:   10 + (0 to 89)
Length = 3:   100 + (0 to 899)
Length = 4:   1000 + (0 to 8999)

and a further step

Length = 2:   10     + (0 to     90-1)
Length = 3:   100   + (0 to     900-1)
Length = 4:   1000 + (0 to     9000-1)

and further again...

Length = 2:   10      + (0 to     (100 - 10)     -1)
Length = 3:   100    + (0 to     (1000 - 100)  -1)
Length = 4:   1000  + (0 to     (10000 - 1000) -1)

and finally:

Length = 2:   10^(2-1)  + (0 to     (10^2 - 10^(2-1)) -1)
Length = 3:   10^(3-1)  + (0 to     (10^3 - 10^(3-1)) -1)
Length = 4:   10^(4-1)  + (0 to     (10^4 - 10^(4-1)) -1)

in code:

Length = 2:   10^(2-1)  + r.Next(0,10^2 - 10^(2-1))    ' Negate 1 because of range being less than max
Length = 3:   10^(3-1)  + r.Next(0,10^3 - 10^(3-1))
Length = 4:   10^(4-1)  + r.Next(0,10^4 - 10^(4-1))

-----------

Well i think you get what im trying to get it... it should just save using the loop:


 
    Dim randMax As Integer
    Dim baseShift As Integer

    Public Function numGenerate(ByVal length As Integer) As Integer
        Dim r As New Random

        If length = 1 Then
            Return  r.Next(0, 10)
        Else
            baseShift = 10^ (length-1)
            randMax  = 10^ length - baseShift

            Return baseShift + r.Next(0, randMax)
         End If
    End Function
 
 ===========

I think that's a different implementation to give the same answer as yours Idle (I've just woken up so apologies if it's slightly off) ... not sure which has a better performance... one advantage of yours over mine is that if the function were just to return a string representation of a random number of a certain length (i.e. don't parse it back to an integer), the length of the random number isn't confined to the range of integer values, but instead to the length of a string
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
S-TwilleyCommented:
I think you should have at least split the points as other experts had given valid points in this question... even if you used my implementation... I (at least my opinion) is that you should give credit to others when it's due. Maybe im being too fair :P
0
EnniobozzettiAuthor Commented:
One question, if I want to display some letter too, what is the best way, using an array with the letters, or using the ASCII char?
0
S-TwilleyCommented:
depends... you'd need to give a bit more info on why u need to display just a letter... really its up to you the programmer, whatever is easier

0
EnniobozzettiAuthor Commented:
well what I'm trying to do is to generate a password, random .
and it would need to be numbers and letters.
0
S-TwilleyCommented:
Dim randGenerator As New Random

 Function GetRandomLetter() As String
        Dim myCharSet As String = "abcdefghijklmnopqrstuvwxyz0123456789"

        Dim randomLetter As Integer = randGenerator.Next(0, myCharSet.Length)
        Return myCharSet.Chars(randomLetter).ToString
    End Function

=============

Just alter the myCharSet string to contain the possible characters... the random generator has been changed to reflect changes in the string... then use the same function GetRandomWord from the other post
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.