Jump to content

Random number gen question

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
8 replies to this topic

#1
nemr118

nemr118

    Newbie

  • Members
  • PipPip
  • 10 posts
Hi all
I'm trying to get a random number generator to work that doesn't return any of the same values.
Here's what I have, but it doesn't work.
Dim intRand As Integer

            Dim temp As String

            Dim strUSED As String

            'get random unused number

            Do

                Randomize()

                intRand = CInt(Int(20 * Rnd()) + 1)

                temp = CStr(InStr(strUSED, CStr(intRand)))


                If temp = Nothing Then

                    strUSED &= intRand

                End If


            Loop Until temp = Nothing

The idea behind it is, it takes the random number between 1-20, checks in strUSED if its there, if it is, temp gets a value, and it loops to random again.

Thanks

#2
nemr118

nemr118

    Newbie

  • Members
  • PipPip
  • 10 posts
This is in VB 2008 btw

#3
nemr118

nemr118

    Newbie

  • Members
  • PipPip
  • 10 posts
I figured it out, InStr sets temp to 0 if the numbers aren't there, making my loop endless

#4
Termana

Termana

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 4,057 posts
if this is vb.net why not just use the System.Random class?
Posted via CodeCall Mobile

#5
nemr118

nemr118

    Newbie

  • Members
  • PipPip
  • 10 posts
Can you give me a example showing that? I haven't learned that yet.

#6
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,248 posts
Google it. Random Class

:)

#7
nemr118

nemr118

    Newbie

  • Members
  • PipPip
  • 10 posts
the class still repeats, so that doesn't really change anything.

What I'm looking for is to click a button, and have it generate a value from 1 to 20. then when i click the button again, it has a value from 1 to 20, but doesn't use any previously given values.

(im making a program for my little sister to do her spelling words with)

#8
Xav

Xav

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 13,118 posts
Dim rand As New System.Random(Now.Millisecond)

Dim number As Integer = rand.Next(1,21)

The lower bound is inclusive, the upper bound is exclusive. Now.Millisecond is a seed that allows for more pseudo-random results.
Jordan said:

Good members, like yourself, stick around and post for ages to come!
Mr. Xav | Blog | Forums

#9
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
I would create an array of the values 1-20 and randomly generate an index. Remove that index item, move the other items down, and now generate a random number from 1-19 (for the index), then 1-18, etc.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog