Welcome Guest ( Log In | Register )



2 Pages V   1 2 >  
Reply to this topicStart new topic
> Visual Basic: Random Strings!
ViRuaL
post May 16 2005, 07:57 PM
Post #1


Newbie [ Level 2 ]
Group Icon

Group: Members
Posts: 19
Joined: 12-May 05
Member No.: 5,018



This article will teach you how to get random strings for output to a label caption, or anywhere you want it to go.

1. First we need to declare our string names:
CODE
Private RndString(2)

This declaration says there will be an array of strings called RndString, and there will be 2 strings in that array.

2. Then, we need to create a function that will generate a random number.
CODE
Private Function RandomNumber(rUpper As Integer, Optional rLower As Integer) As Integer

' Generate random number between upper and lower bound values
   Randomize
   RandomNumber = Int((rUpper - rLower + 1) * Rnd + rLower)
End Function

This initializes the Randomize engine, then picks a random number between the upper and lower bound values that you specify.

3. Now we need to define our strings. You'll most likely want them to be defined on form load, but if need be you may put them on a button click or something.
CODE
Private Sub Form_Load()
RndString(1) = "Yes"
RndString(2) = "No"
End Sub

This defines our strings for later use.

4. Now let's say you want to change a label's caption when a user clicks a button, to one of the random strings we have previously defined. The code would look something like this:
CODE
Command1_Click()
Dim RndNum As Integer
RndNum = RandomNumber(2, 1)
Label1.Caption = RndString(RndNum)
End Sub

This is where the magic happens. RndNum is used to define the index of the string array, and we set it's value equal to a random number, either 2 or 1. Then Label1's Caption becomes the string index of whatever number was produced from the randomize engine.

All done! If you need help with this code or anything else, e-mail me at ViRuaL@gmail.com
Go to the top of the page
 
+Quote Post
Legend
post Aug 27 2005, 11:49 AM
Post #2


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 3
Joined: 27-August 05
From: New Brunswick, Canada
Member No.: 8,137



Hey thats nice! Well... I was doing it like that:
I was doing a random number, and then I was saying
If RandomNumber = 1 then
String = "Yes"
ElseIf RandomNumber = 2 then
String = "No"
End If

It's easier your way happy.gif
Go to the top of the page
 
+Quote Post
iGuest
post Oct 17 2007, 05:25 PM
Post #3


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 0
Joined: 1-November 07
Member No.: 25,869



Hey! nice code, I'm kinda new to VB, I did a little coding on my work experience in school a few months ago and I really liked it. Anyway, want I want to do is to create a program that when a button is pressed on the form, a "random" name or sentence from a database will appear in a textbox or something. I don't know how to do it, so this is why I'm asking :P.

This is an example of something I would like to create: www.factorizer.com

Thank you for your help,
Sam

-SamDave
Go to the top of the page
 
+Quote Post
iGuest
post Jan 4 2008, 01:03 PM
Post #4


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 0
Joined: 1-November 07
Member No.: 25,869



i have a doubt about randomly generating a string
Visual Basic: Random Strings!

I'm writing a code to display 4 options in radiobuttons , that means I have 4 radiobuttons , I want to generate the answer randomly each time different answers but there much be one answer is correct that means that answer will not be randomly generated ..

My question is how to generate the random strings and keep track of one the right answer .. Even that right answer should not be static (it should be every time in different radiobutton) so the person who's answering the quiz will not be able to remember the place of the radiobutton which has the correct answer .
So will you Please tell me how to do that .
The second question is :
If I want to generate random picture in vb.Net .. How can I do that


-noor
Go to the top of the page
 
+Quote Post
turbopowerdmaxst...
post Jan 5 2008, 02:37 PM
Post #5


Premium Member
Group Icon

Group: [HOSTED]
Posts: 392
Joined: 16-February 06
From: Kolkata, India
Member No.: 11,322



We can only generate Random numbers within a specified range. However, this number can be used as the index for an array so that we can select a random element from the array, be it an array of Strings, Images, or whatever. What I mean to say is that the process to selecting random picture is the same as that of selecting random strings.

Another thing that I must mention is that this whole stuff we have seen above is not generating a random string, rather selecting a random string. Generating random strings would generate something like zxjhtsjbdjgasd or asdxcbjdkhasd. You can however, select a dictionary word from a list or an array. But, it wouldn't be generating either.

Back to the first question:-

I am assuming you have a collection of wrong answers and a correct answer for each question. (You don't want to make the correct one obvious by filling the wrong ones with those randomly generated strings we just saw, do you?) You need to shuffle the correct answer's position (1, 2, 3 or 4) each time and you need to select 3 wrong answers from the wrong answer collection.

I'll be using the function created by ViRuaL.

STEP 1: First we generate the random position of the correct answer and store it in our variable: Dim CorrectCh As Integer = RandomNumber(1, 4)

STEP 2: Set the correct answer as the text for the appropriate Radio Button: Options(CorrectCh - 1).Text = CorrectAnswer

(Assuming Options to be a zero based array of Radio Buttons)

STEP 3: For each of the remaining positions, generate a random number. Using this number we select a random answer from the list/array of wrong answers and set the text of the Radio Buttons accordingly.

CODE
For I As Integer = 1 To 4
    If I = CorrectCh Continue For
    Dim Ch As Integer = RandomNumber(0, WrongAnswers.Length - 1)
    Dim WrongAnswer As String = WrongAnswers(Ch)
    Options(I).Text = WrongAnswer
Next I


Although this code is still not bug free. There's a pretty good chance that the same wrong answer will be repeated. This is because generating a Random Number makes no guarantee that it won't be repeated in the next iteration. To resolve this you can follow either of the ways:-

Method 1

Store the selected answers or their IDs in another array. Whenever a new choice is generated, make sure that this number has not been already generated. If it has been then repeat the process again.

CODE
Dim SelectedWrongAnswers As New List(Of Integer)
For I As Integer = 1 To 4
    If I = CorrectCh Continue For
Retry:
    Dim Ch As Integer = RandomNumber(0, WrongAnswers.Length - 1)
    For J as Integer = 0 To SelectedWrongAnswers.Length - 1
        If SelectedWrongAnswers(J) = Ch Then
            Goto Retry
        End If
    Next J
    SelectedWrongAnswers.Add(Ch)
    Dim WrongAnswer As String = WrongAnswers(Ch)
    Options(I).Text = WrongAnswer
Next I


The inner loop can be eliminated by using a HashTable as follows:-

CODE
Dim SelectedWrongAnswers As New HashTable
For I As Integer = 1 To 4
    If I = CorrectCh Continue For
Retry:
    Dim Ch As Integer = RandomNumber(0, WrongAnswers.Length - 1)
    If SelectedWrongAnswers(Ch) <> Nothing Then
        Goto Retry
    End If
    Dim WrongAnswer As String = WrongAnswers(Ch)
    SelectedWrongAnswers.Add(Ch, WrongAnswer)
    Options(I).Text = WrongAnswer
Next I


Method 2

This Method is not quite efficient, because the Retry operation may take many iterations if an already generated random number is being generated again. So a better approach is to use a class that generates a non random number. You can find the VB .NET and C# . NET implementation of such a class at http://maxotek.net/blog/?p=9

The following code uses the RandomNumber class declared at http://maxotek.net/blog/?p=9

CODE
Dim WrongAnswerGenerator As New RandomNunber(0, WrongAnswers.Length - 1)
For I As Integer = 1 To 4
    If I = CorrectCh Continue For
    Dim Ch As Integer = WrongAnswerGenerator.GetRandomNumber()
    Dim WrongAnswer As String = WrongAnswers(Ch)
    Options(I).Text = WrongAnswer
Next I
Go to the top of the page
 
+Quote Post
Chesso
post Jan 5 2008, 09:49 PM
Post #6


Teh Coder
Group Icon

Group: Members
Posts: 1,053
Joined: 18-April 06
From: Australia
Member No.: 12,833



I have not done VB in a long time, but I assume you can make object arrays (filled with strings and what not), or record arrays maybe.

Use that instead of if/then/else if, and if you have something available like record arrays, add an extra value for primary (or the answer), so say if you load 4 strings from file, 1 will be marked in some manner as the correct answer, mark it as primary.

Then if someone checks a box, check the correspendence between radio button and record array, and check it's primary property to see if it's the correct answer.

Anyway, I do all this stuff in Object Pascal (Delphi), but VB should have something.
Go to the top of the page
 
+Quote Post
iGuest
post Feb 26 2008, 06:11 PM
Post #7


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 0
Joined: 1-November 07
Member No.: 25,869



Word (Integer)
Visual Basic: Random Strings!

I am currently trying to make a spelling program in which it has 3 levels .
What I'm stuck at is when it comes to coding it how do I get it so words are shown on a label then took off in which you can then right in the text box what word it was. How do I then have random words come up but not have them show again so that the person isnt seeing the same word over and over again.

-question by Paul
Go to the top of the page
 
+Quote Post
turbopowerdmaxst...
post Feb 27 2008, 09:45 PM
Post #8


Premium Member
Group Icon

Group: [HOSTED]
Posts: 392
Joined: 16-February 06
From: Kolkata, India
Member No.: 11,322



You need to generate non-repeating Random numbers. I made a class for the same which can generate non-repeating Random numbers within a specified range or select a non-repeating Random number from a supplied list of numbers. The numbers will be repeated after a complete cycle finishes and all the numbers have been generated once.

You can find the VB.NET code at http://maxotek.net/blog/?p=9

You could modify the code a bit to directly select one of your words stored as string types.

CODE
Public Class RandomNumber
    Dim WordDomain As New ArrayList      ' The Words to be generated
    Dim Words As New ArrayList           ' The Words waiting to be generated

    Sub New(ByVal ParamArray Words() As String)
        ' Words in a Param Array
        Dim Word As String
        For Each Word In Words
            WordDomain.Add(Word)
        Next

        AddItems()
    End Sub

    Sub New(ByVal Words() As String)
        ' Words in a String Array
        Dim Word As String
        For Each Word In Words
            WordDomain.Add(Word)
        Next

        AddItems()
    End Sub

    Private Sub AddItems()

        Words.Clear()
        ' Insert All Words Into the Array
        Dim I As Integer
        For I = 0 To WordDomain.Count - 1
            Words.Add(WordDomain(I))
        Next
    End Sub

    Public Function GetRandomWord() As String
        If Words.Count = 0 Then
            ' Re-add the Items, when all the words have been generated.
            AddItems()
        End If

        ' Return a Random Item and Remove it from the List
        Dim Ch As Integer

        ' Using Timer as the seed for the Random Number Generation
        Randomize(Microsoft.VisualBasic.Timer)

        ' Random Number is generated within the range.
        Ch = 0 + CInt(Rnd() * (Words.Count - 1))

        Dim Word As String = Words(Ch)
        Words.RemoveAt(Ch)
        Return Word
    End Function
End Class


The above code generates Random words based on a supplied list using a String array or as a ParamArray.
Go to the top of the page
 
+Quote Post
iGuest
post Mar 14 2008, 07:43 AM
Post #9


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 0
Joined: 1-November 07
Member No.: 25,869



random function using in automatically selected question in vb 6.o version
Visual Basic: Random Strings!

Replying to Feedbacker you have a query of question and this query is selected by using random function.

-question by santu
Go to the top of the page
 
+Quote Post
iGuest
post Apr 15 2008, 04:01 AM
Post #10


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 0
Joined: 1-November 07
Member No.: 25,869



[Replying to turbopowerdmaxsteel,5264,119 669] I tried to use the code you wrote but I get an error on the word New after the Sub New. I have tried several corrections but can't figure it out. What I really want is a way to have a list of 12 or 16 names that can be randomly sorted for a game, so that partners will be different each month. I wrote one in Quick Basic and it worked great but programs written in QB can't be printed through Windows. I would really like to find a way to make one in vb2005Express.

-question by JRichards
Go to the top of the page
 
+Quote Post

2 Pages V   1 2 >
Reply to this topicStart new topic

Collapse

> Similar Topics

Topics Topics
  1. [visual Basic] How To Confirm A Array Is Null(6)
  2. Visual Basic Help(7)
  3. Visual Basic: Replace Explained!(4)
  4. Visual Basic: Unload Your Application Correctly!(1)
  5. Visual Basic: Change Your Start Button Text! (XP)(16)
  6. Visual Basic 6 + Crystal Reports 9(6)
  7. Visual Basic Names(11)
  8. New Features In Visual Studio 2005 Windows Forms(1)
  9. Visual Basic.NET Help Needed.(7)
  10. Is There A Free IDE For VB.NET Programming?(4)
  11. Visual Basic Express Tutorials(5)
  12. [help] Visual Studio .net 2005 Questions(8)
  13. Installed Internet Explorer 7?, Visual Basic Now Broken?(3)
  14. Visual Basic Projects: Scoreboard(0)
  15. Delete A Registry Subkey And Key(8)
  1. Necklace Problem In Visual Basic(3)


 



- Lo-Fi Version Time is now: 12th October 2008 - 02:17 AM