Results 1 to 15 of 15

Thread: Using time to determine a 'random' number

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Using time to determine a 'random' number

    Sometimes an opportunity presents itself where you have two answeres and it doesn't really matter which one you use. A good example could be find b in the y=mx+b formula to determain the equation of line between two points. Or in my example, asking "Which came first, the chicken or the egg?"

    Code:
    'Here I just store two answeres
    Dim str() As String = {"The Chicken", "The Egg"}
    
    'Here I get the millisecond
    Dim timeNow As Integer = DateTime.Now.Millisecond
    
    'Here I use the Mod operator to check if the millisecond is odd or even
    If CBool(timeNow Mod 3) Then
        MessageBox.Show(str(0), "Which came first?")
    Else
        MessageBox.Show(str(1), "Which came first?")
    End If

    Update:
    It has been nearly 9 years since I originally wrote this and I marvel at how far I have come. This is how I would rewrite the code snippet today:
    Code:
    Public Class RandomOption
        Public Shared Function NextRandom(Of T)(options As IEnumerable(Of T)) As T
            If (options.Count() < 2) Then
                Throw New ArgumentException("The underlying collection must have at least two (2) items.")
            End If
    
            Dim skip = If(DateTime.Now.Ticks Mod 3 = 0, 0, 1)
            Return options.Skip(skip).First()
        End Function
    End Class
    This is how the class could be used, using the same chicken/egg example:
    Code:
    Console.Write("Which came first: ")
    
    Dim answer = RandomOption.NextRandom(Of String)({"Chicken", "Egg"})
    Console.WriteLine(answer)
    Fiddle: https://dotnetfiddle.net/7wGlsU
    Last edited by dday9; Aug 3rd, 2021 at 09:28 AM.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  2. #2

    Re: Using time to determine a 'random' number

    I'm a little curious as to why you didn't make use of the Random() class, but, you're using time to determine a choice (which, funnily enough, the Random() class has an overload to take a seed, while, if I recall correctly, the default constructor will use the system time as the seed). While that is technically psuedo-random, it can be abused to to get a desired result. Otherwise, a nice small snippet to the Codebank. I recommend you find a way to wrap this up in a class and allow someone to give it a List(Of T) and, using that method, try to see if it will give you random choices.

    A nice little exercise, if you ask me.

  3. #3

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Re: Using time to determine a 'random' number

    Thanks for the reply. Reason I didn't use the Random class is because I try to avoid as much as possible. I know in many cases it's best to use Random, but in the case of determain the equation of line example I gave above I was able to avoid it. I will try to wrap it up in a class, seems challenging what you've proposed... I like it! But again, thanks for the reply.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  4. #4

    Re: Using time to determine a 'random' number

    Quote Originally Posted by dday9 View Post
    Thanks for the reply. Reason I didn't use the Random class is because I try to avoid as much as possible. I know in many cases it's best to use Random, but in the case of determain the equation of line example I gave above I was able to avoid it. I will try to wrap it up in a class, seems challenging what you've proposed... I like it! But again, thanks for the reply.
    Just curious, why do you want to avoid it? Is there a particular reason you dislike it?

  5. #5

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Re: Using time to determine a 'random' number

    Because there is never truely a random number. Everything happens because an event triggered it to happen. Not anything to the .Net random, just a personal knitpick.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  6. #6

    Re: Using time to determine a 'random' number

    Quote Originally Posted by dday9 View Post
    Because there is never truely a random number. Everything happens because an event triggered it to happen. Not anything to the .Net random, just a personal knitpick.
    In all fairness, you can't get true randomness with this either, in any language. You can get really good randomization (Blum Blum Shub, and Mersenne Twister are two good implementations of very good, strong randomization algorithms) if you know what you're doing.

    If you really want extremely good (but slow) randomization, you're going to need hardware to do it. Otherwise, the .NET randomization class (which I believe implements a Linear Congruential Generator, described here) is pretty good for most needs.

  7. #7

    Re: Using time to determine a 'random' number

    Also, if you want examples for the Mersenne Twister and Blum Blum Shub, I'll be more than happy to post them in the codebank later today when I get home from work.

  8. #8

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Re: Using time to determine a 'random' number

    Mais yeah, I love to see some examples. I love studying the art of "randomizing"
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  9. #9
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,961

    Re: Using time to determine a 'random' number

    Quote Originally Posted by dday9 View Post

    VB.Net Code:
    1. 'Here I use the Mod operator to check if the millisecond is odd or even
    2.         If CBool(timeNow Mod 3) Then ...
    You need to use Mod 2 to check for odd/even, not Mod 3.

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: Using time to determine a 'random' number

    Quote Originally Posted by dday9 View Post
    Because there is never truely a random number. Everything happens because an event triggered it to happen. Not anything to the .Net random, just a personal knitpick.
    That really doesn't make sense. How is your algorithm any more random than using the Random class? You know ahead of time exactly what value will be returned for every time of the day.

  11. #11
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: Using time to determine a 'random' number

    Hi dday, adding to your woes:

    1. It's better to use DateTime.Ticks because a lot of code can be processed in a millisecond. Your code with messageboxes won't show this because you stop the code, but in other circumstances you could easily end up with all eggs or all chickens!

    2. The example of the line formula y = mx + b is not good because it has only one solution for b. There are other line formulas involving angles where there could be two solutions, corresponding to the directions AB or BA. You would usually use those when the direction does matter. If it really doesn't matter, you don't need a randomizer because you can take whichever solution comes first.

    BB

  12. #12

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Re: Using time to determine a 'random' number

    Thanks for all of y'alls suggestions and input. I know that this isn't "random", but I did find it unique. I will state again, that I have a huge intrest in randoms and randomizing. This is just an extension of my intrest.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  13. #13

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Re: Using time to determine a 'random' number

    I have updated original post to include how I would do this today.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  14. #14
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Using time to determine a 'random' number

    You have come a long way. Proud of you my child
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  15. #15
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: Using time to determine a 'random' number

    If the Random class is not random enough for you - it absolutely is for the vast majority of applications - then you should be using the RNGCryptoServiceProvider class. It is what's used to generate random numbers for cryptography in .NET. It is random enough for you.

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