Random number problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • tshad

    #1

    Random number problem

    I am trying to create some random numbers to create an ID and am having
    problems with getting the same number over and over.

    I have a function:

    Function RandomNumber(mi n as Integer, max as Integer) as integer
    Dim random as Random = new Random()
    RandomNumber = random.Next(min , max)
    End Function

    If I call this 3 times:

    id = RandomNumber(0, 10))
    id = RandomNumber(0, 10))
    id = RandomNumber(0, 10))

    I will get the same number each time.

    I assume this is because it is based on the clock and uses the same seed if
    call one after another. Is there a good way around this?

    Thanks,

    Tom


  • AMercer

    #2
    RE: Random number problem

    > I am trying to create some random numbers to create an ID and am having[color=blue]
    > problems with getting the same number over and over.
    >
    > Function RandomNumber(mi n as Integer, max as Integer) as integer
    > Dim random as Random = new Random()
    > RandomNumber = random.Next(min , max)
    > End Function
    >[/color]

    Replace Dim with Static:
    Static random As New Random
    What you want to do is call random.Next on the same object over and over
    again. You don't want to make a new instance at every call.

    Comment

    • tshad

      #3
      Re: Random number problem

      "AMercer" <AMercer@discus sions.microsoft .com> wrote in message
      news:2DC502DF-7C61-4D08-8C17-9F1D694F24B9@mi crosoft.com...[color=blue][color=green]
      >> I am trying to create some random numbers to create an ID and am having
      >> problems with getting the same number over and over.
      >>
      >> Function RandomNumber(mi n as Integer, max as Integer) as integer
      >> Dim random as Random = new Random()
      >> RandomNumber = random.Next(min , max)
      >> End Function
      >>[/color]
      >
      > Replace Dim with Static:
      > Static random As New Random
      > What you want to do is call random.Next on the same object over and over
      > again. You don't want to make a new instance at every call.[/color]

      That was what I needed.

      Thanks,

      Tom


      Comment

      • Jim Wooley

        #4
        Re: Random number problem

        > I am trying to create some random numbers to create an ID and am[color=blue]
        > having problems with getting the same number over and over.
        >
        > I assume this is because it is based on the clock and uses the same
        > seed if call one after another. Is there a good way around this?[/color]

        In 2005, you may want to look into the Cryptography namespace, specifically
        System.Security .Cryptography.R andomNumberGene rator. It is more reliable in
        terms of creating true random results.

        Jim Wooley


        Comment

        Working...