?
Solved

Need some help.

Posted on 2005-04-01
11
Medium Priority
?
347 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
[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
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses
Course of the Month11 days, 11 hours left to enroll

752 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