Results 1 to 15 of 15

Thread: Using time to determine a 'random' number

Threaded View

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,374

    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 | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

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