Results 1 to 26 of 26

Thread: Random string function... not random

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Feb 2009
    Posts
    28

    Random string function... not random

    hey
    i am using the below function to generate a random string of x amount of charactors:
    Code:
    Function RandomString(ByVal mask As String) As String
        Dim i As Integer
        Dim acode As Integer
        Dim options As String
        Dim char As String
        
        ' initialize result with proper lenght
        RandomString = mask
        
        For i = 1 To Len(mask)
            ' get the character
            char = Mid$(mask, i, 1)
            Select Case char
                Case "?"
                    char = Chr$(1 + Rnd * 127)
                    options = ""
                Case "#"
                    options = "0123456789"
                Case "A"
                    options = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
                Case "N"
                    options = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0" _
                        & "123456789"
                Case "H"
                    options = "0123456789ABCDEF"
                Case Else
                    
                    options = ""
            End Select
        
            
            If Len(options) Then
                
                char = Mid$(options & Right$(options, 1), 1 + Int(Rnd * Len(options) _
                    ), 1)
            End If
                   
            Mid(RandomString, i, 1) = char
        Next
    
    End Function
    problem is every time i call the function it produce the same output each time.. not random at all

  2. #2
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: Random string function... not random

    Wow, get to answer this one twice today.

    In your form load event, ensure you use Randomize. Suggest adding this in Form_Load: Randomize Timer

    The Randomize method seeds the random generator with the value passed, in this case the VB variable Timer.

    Edited: Just a minute, do you mean you get the same results every single time? Or do you get the same results each time you start the project?
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  3. #3

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Feb 2009
    Posts
    28

    Re: Random string function... not random

    MsgBox "IS this random???!" & RandomString("#ANH")

    each time i run i get same result..

    tried randomizing the timer also.

  5. #5

  6. #6
    PowerPoster Code Doc's Avatar
    Join Date
    Mar 2007
    Location
    Omaha, Nebraska
    Posts
    2,354

    Re: Random string function... not random

    Quote Originally Posted by LaVolpe
    Wow, get to answer this one twice today.

    In your form load event, ensure you use Randomize. Suggest adding this in Form_Load: Randomize Timer

    The Randomize method seeds the random generator with the value passed, in this case the VB variable Timer.

    Edited: Just a minute, do you mean you get the same results every single time? Or do you get the same results each time you start the project?
    Fox, I don't think the Randomize Timer is needed anymore. Just Randomize by itself in the Form Load will work to generate a different sequence.
    Doctor Ed

  7. #7
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: Random string function... not random

    Probably not, per MSDN docs, if I recall, Randomize without a parameter will use the system clock to seed the generator.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  8. #8
    Fanatic Member technorobbo's Avatar
    Join Date
    Dec 2008
    Location
    Chicago
    Posts
    864

    Re: Random string function... not random

    Brinx

    I'm not sure what you meant by:
    tried randomizing the timer also.
    but try putting the randomize command here:
    Code:
    Function RandomString(ByVal mask As String) As String
        Dim i As Integer
        Dim acode As Integer
        Dim options As String
        Dim char As String
    
        Randomize
    
        ' initialize result with proper lenght
        RandomString = mask
        
        For i = 1 To Len(mask)
            ' get the character
            char = Mid$(mask, i, 1)
            Select Case char
                Case "?"
                    char = Chr$(1 + Rnd * 127)
                    options = ""
                Case "#"
                    options = "0123456789"
                Case "A"
                    options = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
                Case "N"
                    options = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0" _
                        & "123456789"
                Case "H"
                    options = "0123456789ABCDEF"
                Case Else
                    
                    options = ""
            End Select
        
            
            If Len(options) Then
                
                char = Mid$(options & Right$(options, 1), 1 + Int(Rnd * Len(options) _
                    ), 1)
            End If
                   
            Mid(RandomString, i, 1) = char
        Next
    
    End Function
    Have Fun,

    TR
    _____________________________
    Check out my Alpha DogFighter2D Game Demo and Source code. Direct Download:http://home.comcast.net/~technorobbo/Alpha.zip or Read about it in the forum:http://www.vbforums.com/showthread.php?t=551700. Now in 3D!!! http://home.comcast.net/~technorobbo/AlPha3D.zip or read about it in the forum: http://www.vbforums.com/showthread.php?goto=newpost&t=552560 and IChessChat3D internet chess game

  9. #9
    "Digital Revolution"
    Join Date
    Mar 2005
    Posts
    4,471

    Re: Random string function... not random

    The Randomize statement should only be used once and when the program starts like in Form_Load() as LaVolpe said.

  10. #10
    Fanatic Member technorobbo's Avatar
    Join Date
    Dec 2008
    Location
    Chicago
    Posts
    864

    Re: Random string function... not random

    Really why? It can be used that way to repeat patterns. So why not insert it where he can see it in his code and understand what we're saying.


    Here's the MSDN Link http://msdn.microsoft.com/en-us/libr...ek(VS.85).aspx
    Have Fun,

    TR
    _____________________________
    Check out my Alpha DogFighter2D Game Demo and Source code. Direct Download:http://home.comcast.net/~technorobbo/Alpha.zip or Read about it in the forum:http://www.vbforums.com/showthread.php?t=551700. Now in 3D!!! http://home.comcast.net/~technorobbo/AlPha3D.zip or read about it in the forum: http://www.vbforums.com/showthread.php?goto=newpost&t=552560 and IChessChat3D internet chess game

  11. #11
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: Random string function... not random

    Quote Originally Posted by technorobbo
    Really why? It can be used that way to repeat patterns. So why not insert it where he can see it in his code and understand what we're saying.


    Here's the MSDN Link http://msdn.microsoft.com/en-us/libr...ek(VS.85).aspx
    Well that link is for .Net but in any case it has been shown that using Randomize more than once actually makes for a less random output and there's a thread somewhere that proves it.

  12. #12
    Fanatic Member technorobbo's Avatar
    Join Date
    Dec 2008
    Location
    Chicago
    Posts
    864

    Re: Random string function... not random

    Quote Originally Posted by MartinLiss
    Well that link is for .Net but in any case it has been shown that using Randomize more than once actually makes for a less random output and there's a thread somewhere that proves it.
    It may be for .Net my VB5 doc is identical. As I always say Random is a misnomer. It should be called AlmostUnpredictable. And less Random would be an oxymoron. More predictable makes more sense but that would kind of depend on the application.
    Have Fun,

    TR
    _____________________________
    Check out my Alpha DogFighter2D Game Demo and Source code. Direct Download:http://home.comcast.net/~technorobbo/Alpha.zip or Read about it in the forum:http://www.vbforums.com/showthread.php?t=551700. Now in 3D!!! http://home.comcast.net/~technorobbo/AlPha3D.zip or read about it in the forum: http://www.vbforums.com/showthread.php?goto=newpost&t=552560 and IChessChat3D internet chess game

  13. #13
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Random string function... not random

    Quote Originally Posted by MartinLiss
    Well that link is for .Net but in any case it has been shown that using Randomize more than once actually makes for a less random output and there's a thread somewhere that proves it.
    No actually its VBScript.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  14. #14
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: Random string function... not random

    Quote Originally Posted by Atheist
    No actually its VBScript.
    Okay but it doesn't really matter since it doesn't support either side of the argument. I'll find the thread I was talking about when I have the time.

  15. #15
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Random string function... not random

    From My Database...

    Code:
    Private Sub Command1_Click()
        '~~ For example generate a string of 10 chars
        MsgBox GenerateRandomString(10)
    End Sub
    
    Private Function GenerateRandomString(ByVal lngLength As Long) As String
        Dim iChr As Integer, c As Long, strResult As String, iAsc As String
     
        Randomize Timer
    
        For c = 1 To lngLength
            '~~> Randomly decide on ASCII chars to be used
            iAsc = Int(3 * Rnd + 1)
       
            '~~> Randomly pick a char from the random set
            Select Case iAsc
            Case 1
                iChr = Int((Asc("Z") - Asc("A") + 1) * Rnd + Asc("A"))
            Case 2
                iChr = Int((Asc("z") - Asc("a") + 1) * Rnd + Asc("a"))
            Case 3
                iChr = Int((Asc("9") - Asc("0") + 1) * Rnd + Asc("0"))
            End Select
       
            strResult = strResult & Chr(iChr)
        Next c
        GenerateRandomString = strResult
    End Function
    Another one from the same database

    Code:
    Private Sub Command1_Click()
        '~~ For example generate a string of 10 chars
        MsgBox GenerateRandomString(10)
    End Sub
    
    Function GenerateRandomString(ByRef length As Integer) As String
        Randomize
        
        Dim allowableChars As String
        
        allowableChars = "abcdefghijklmnopqrstuvwxyz0123456789"
     
        Dim i As Integer
        For i = 1 To length
            GenerateRandomString = GenerateRandomString & _
            Mid$(allowableChars, Int(Rnd() * Len(allowableChars) + 1), 1)
        Next
    End Function
    Last edited by Siddharth Rout; Feb 28th, 2009 at 12:21 PM.
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  16. #16
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: Random string function... not random

    Quote Originally Posted by MartinLiss
    Okay but it doesn't really matter since it doesn't support either side of the argument. I'll find the thread I was talking about when I have the time.
    I'm betting it's this one:

    Proper use of the Randomize Statement

    As demonstrated in that thread, calling Randomize only once results in a nice, smooth distribution of random numbers. Calling Randomize inside the loop results in a more spiky distribution.

  17. #17
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: Random string function... not random

    Quote Originally Posted by Ellis Dee
    I'm betting it's this one:

    Proper use of the Randomize Statement

    As demonstrated in that thread, calling Randomize only once results in a nice, smooth distribution of random numbers. Calling Randomize inside the loop results in a more spiky distribution.
    Yes, thank you!

  18. #18
    Fanatic Member technorobbo's Avatar
    Join Date
    Dec 2008
    Location
    Chicago
    Posts
    864

    Re: Random string function... not random

    I think the point of that article is for generating Gaussian Normal Disributions. Hence the even peaks. Personally i would prefer something closer to a white noise pattern. Erratic distribution
    Have Fun,

    TR
    _____________________________
    Check out my Alpha DogFighter2D Game Demo and Source code. Direct Download:http://home.comcast.net/~technorobbo/Alpha.zip or Read about it in the forum:http://www.vbforums.com/showthread.php?t=551700. Now in 3D!!! http://home.comcast.net/~technorobbo/AlPha3D.zip or read about it in the forum: http://www.vbforums.com/showthread.php?goto=newpost&t=552560 and IChessChat3D internet chess game

  19. #19
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: Random string function... not random

    I don't follow. Let's say we're simulating dice. You'd rather some of the numbers come up more frequently than others than to have a more even distribution? Isn't that effectively using loaded dice?

  20. #20
    Fanatic Member technorobbo's Avatar
    Join Date
    Dec 2008
    Location
    Chicago
    Posts
    864

    Re: Random string function... not random

    The frequency shouldnt be predictable. It should be chaotic.The way I read the MS algorithm there's a built in cycle of 2^24. Randomize should shake it up as long as it's not in a fixed loop.
    Last edited by technorobbo; Feb 28th, 2009 at 03:02 PM.
    Have Fun,

    TR
    _____________________________
    Check out my Alpha DogFighter2D Game Demo and Source code. Direct Download:http://home.comcast.net/~technorobbo/Alpha.zip or Read about it in the forum:http://www.vbforums.com/showthread.php?t=551700. Now in 3D!!! http://home.comcast.net/~technorobbo/AlPha3D.zip or read about it in the forum: http://www.vbforums.com/showthread.php?goto=newpost&t=552560 and IChessChat3D internet chess game

  21. #21
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: Random string function... not random

    An even distribution doesn't make it predictable. It just means that no one number has a higher probability of being generated than another. Think of a single die (dice). Don't you want a 6 to roll once every 6 times on average?

  22. #22
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: Random string function... not random

    Quote Originally Posted by technorobbo
    The frequency shouldnt be predictable. It should be chaotic.The way I read the MS algorithm there's a built in cycle of 2^24. Randomize should shake it up as long as it's not in a fixed loop.
    I don't understand, but I'd like to. What, exactly, do you mean by "frequency" here?

  23. #23
    Fanatic Member technorobbo's Avatar
    Join Date
    Dec 2008
    Location
    Chicago
    Posts
    864

    Re: Random string function... not random

    Dice are chaotic. PRNG's repeat and for games the repetition isn't that vital. For encryption it may be because it is predictable and you can synchronize 2 systems.

    Frequency would mean how often they repeat and if they do repeat can they be hacked and synced by spotting the pattern.

    BTW MS's algotithm (in C) is this (vb can't do plicated cause it doesnt have the unsigned long integer):
    Code:
    #include "stdafx.h"
    
    int main(int argc, char* argv[])
    {
    unsigned long       rndVal;
    
    rndVal = 0x50000L;
    int i;
    float rndFloat;
    
    for (i=0;i<10;i++)
    	{
    	rndVal = (rndVal * 0x43fd43fdL + 0xc39ec3L) & 0xffffffL;
    	rndFloat = (float)rndVal / (float)16777216.0;
    	printf("Value is %.15f\n",rndFloat);
    	}
    return 0;
    }
    Have Fun,

    TR
    _____________________________
    Check out my Alpha DogFighter2D Game Demo and Source code. Direct Download:http://home.comcast.net/~technorobbo/Alpha.zip or Read about it in the forum:http://www.vbforums.com/showthread.php?t=551700. Now in 3D!!! http://home.comcast.net/~technorobbo/AlPha3D.zip or read about it in the forum: http://www.vbforums.com/showthread.php?goto=newpost&t=552560 and IChessChat3D internet chess game

  24. #24
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: Random string function... not random

    Quote Originally Posted by technorobbo
    Dice are chaotic.....
    I may be misunderstanding you but dice are not chaotic. Given enough rolls they are highly predictable in that if I rolled a die 6000 times I'm sure that I'd get 1000 6's or at least pretty close to that.

  25. #25
    Fanatic Member technorobbo's Avatar
    Join Date
    Dec 2008
    Location
    Chicago
    Posts
    864

    Re: Random string function... not random

    Remember what Mark Twain said about statistics. Dice are truly unpredicatble to much input and one little output. But the RND() algorithm is a shuffle. Once the seed is given the numbers come out in a predetermined pattern. Reseeding in an unplanned manner disrupts the sequence. Given its a large pattern but not large enough to avoid detection.
    Have Fun,

    TR
    _____________________________
    Check out my Alpha DogFighter2D Game Demo and Source code. Direct Download:http://home.comcast.net/~technorobbo/Alpha.zip or Read about it in the forum:http://www.vbforums.com/showthread.php?t=551700. Now in 3D!!! http://home.comcast.net/~technorobbo/AlPha3D.zip or read about it in the forum: http://www.vbforums.com/showthread.php?goto=newpost&t=552560 and IChessChat3D internet chess game

  26. #26
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: Random string function... not random

    I'd feel better about calling Randomize after every user interaction (keystroke or mouseclick) than I would about putting it inside the processing loop.

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