Jump to content
xisto Community
ViRuaL

Visual Basic: Random Strings!

Recommended Posts

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:

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.

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.

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:

Command1_Click()Dim RndNum As IntegerRndNum = 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

Share this post


Link to post
Share on other sites

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 IfIt's easier your way :D

Share this post


Link to post
Share on other sites

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: http://forums.xisto.com/no_longer_exists/ you for your help,Sam-SamDave

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

 

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 = WrongAnswerNext 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.

 

Dim SelectedWrongAnswers As New List(Of Integer)For I As Integer = 1 To 4	If I = CorrectCh Continue ForRetry:	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 = WrongAnswerNext I

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

 

Dim SelectedWrongAnswers As New HashTableFor I As Integer = 1 To 4	If I = CorrectCh Continue ForRetry:	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 = WrongAnswerNext 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://forums.xisto.com/no_longer_exists/

 

The following code uses the RandomNumber class declared at http://forums.xisto.com/no_longer_exists/

 

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 = WrongAnswerNext I

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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://forums.xisto.com/no_longer_exists/

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

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 FunctionEnd Class

The above code generates Random words based on a supplied list using a String array or as a ParamArray.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

[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

Share this post


Link to post
Share on other sites

help with selecting random pictures

Visual Basic: Random Strings!

 

Please could someone help with the following question

 

I'm new to VB and need help, My problem is that I need to know how I can write the correct code which enables a button when each time it is pressed, it randomly selects a picture from 6 different pictures and show this on the screen. The pictures are bmp and would be stored on the pc - I have for now put them in c:pictures location with the file names 1.Bmp 2.Bmp etc...

 

I am unsure how to write the correct code to select the pictures at random from the file.

 

 

-question by steve

Share this post


Link to post
Share on other sites
i want to use this concept but as something differentVisual Basic: Random Strings!

okay I want to make it when you enter a name into a text box it displays that name but after that it displays one of to random phrases such as for example if they put in cody it would return cody and then randomly choose between "is cool"or "some thing else"

-reply by nick

Share this post


Link to post
Share on other sites
Listbox with random string Visual Basic: Random Strings!I'm trying to create a program that is a contest. Where you enter names in a input box and they are stored in the listbox. After the names are stored, you click a button and it picks a name at random from the listbox and displays the winner's name in a label. Any ideas?-question by Sherri

Share this post


Link to post
Share on other sites

I'm currently in need of a program for my project...We're to interface a circuit via VB... We know what we want to happen on our program yet we don't know how to encode it already in VB... This is how the program goes...FOR EXAMPLE.. There are THREE set of numbers... And inside those sets were numbers stored...SET I = 1-10SET II = 11-20SET II = 21-30(the numbers inside the sets are just examples... We'll be using Input Values from a Parallel Port/Printer Port... -thinking that using other numbers would affect the changes in the program... But I don't really think so... Anyways...)Upon loading the form... The program will randomly choose one of those sets... After that... The user will input the values inside the chosen set respectively and correctly... I.E... The program randomly got SET II...In a label box... The values 21-30 should show in it respectively( the values are inputted to the label box through text box and a command button)... If it goes wrong... It will automatically terminate the program... Otherwise... A message/event will happen that the values are properly and correctly inputted... I hope you get what I'm actually saying...-reply by jerome

Share this post


Link to post
Share on other sites

I'm currently in need of a program for my project...We're to interface a circuit via VB... We know what we want to happen on our program yet we don't know how to encode it already in VB... This is how the program goes...FOR EXAMPLE.. There are THREE set of numbers... And inside those sets were numbers stored...SET I = 1-10SET II = 11-20SET II = 21-30(the numbers inside the sets are just examples... We'll be using Input Values from a Parallel Port/Printer Port... -thinking that using other numbers would affect the changes in the program... But I don't really think so... Anyways...)Upon loading the form... The program will randomly choose one of those sets... After that... The user will input the values inside the chosen set respectively and correctly... I.E... The program randomly got SET II...In a label box... The values 21-30 should show in it respectively( the values are inputted to the label box through text box and a command button)... If it goes wrong... It will automatically terminate the program... Otherwise... A message/event will happen that the values are properly and correctly inputted... I hope you get what I'm actually saying...

-reply by Jerome

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.