Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Need some help.

Posted on 2005-04-01
11
Medium Priority
?
350 Views
Last Modified: 2010-04-23
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
0
Comment
Question by:Enniobozzetti
  • 5
  • 2
  • 2
  • +2
11 Comments
 
LVL 34

Expert Comment

by:Brian Crowe
ID: 13686289
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
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13686514
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 13686731
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 9

Expert Comment

by:Lacutah
ID: 13687169
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 13688201
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
 
LVL 12

Accepted Solution

by:
S-Twilley earned 200 total points
ID: 13688413
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
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13688550
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
 

Author Comment

by:Enniobozzetti
ID: 13703339
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
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13703360
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
 

Author Comment

by:Enniobozzetti
ID: 13703391
well what I'm trying to do is to generate a password, random .
and it would need to be numbers and letters.
0
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13703418
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

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Kernel Data Recovery is a renowned Data Recovery solution provider which offers wide range of softwares for both enterprise and home users with its cost-effective solutions. Let's have a quick overview of the journey and data recovery tools range he…
How can you see what you are working on when you want to see it while you to save a copy? Add a "Save As" icon to the Quick Access Toolbar, or QAT. That way, when you save a copy of a query, form, report, or other object you are modifying, you…
Suggested Courses
Course of the Month15 days, 20 hours left to enroll

580 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