Nov 21, 2009
Pages: 1, 2

Visual Basic: Random Strings!

free web hosting

Read Latest Entries..: (Post #12) by iGuest on Nov 19 2009, 04:29 AM.
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...
read more.
Read the FIRST post of this Topic. - Express your Opinion! Contribute Knowledge :-).

Open Discussion & Free Web Hosting > Computers & Tech > Programming > Programming General > BASIC / Visual Basic (.NET)

Visual Basic: Random Strings!

ViRuaL
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

 

 

 


Comment/Reply (w/o sign-up)

Legend
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

Comment/Reply (w/o sign-up)

FeedBacker
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

Comment/Reply (w/o sign-up)

FeedBacker
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

Comment/Reply (w/o sign-up)

turbopowerdmaxsteel
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

 

 

 


Comment/Reply (w/o sign-up)

Chesso
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.

Comment/Reply (w/o sign-up)

FeedBacker
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

Comment/Reply (w/o sign-up)

turbopowerdmaxsteel
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.

Comment/Reply (w/o sign-up)

FeedBacker
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

Comment/Reply (w/o sign-up)

FeedBacker
[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

Comment/Reply (w/o sign-up)

Latest Entries

iGuest
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

Comment/Reply (w/o sign-up)

iGuest
i want to use this concept but as something different
Visual 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

Comment/Reply (w/o sign-up)


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Pages: 1, 2
Similar Topics

Keywords : visual, basic, random, strings

  1. Necklace Problem In Visual Basic
    (3)
  2. Delete A Registry Subkey And Key
    Using Visual Basic 2005 Express (8)
    Hi, does anyone know how to delete a registry key/subkey using VB 2005 Express. Also, if any other
    methods using VB, C#, C++, J#, post them as well.....
  3. Visual Basic Projects: Scoreboard
    Making a scoreboard with Visual Basic 6 (0)
    Hi again, I've done another visual basic tutorial in this forum on how to make a simple,
    customized web browser. Now I am going to say how to make a scoreboard. To do so, open a Standard
    EXE project in Visual Basic 6.0 and insert 6 labels and 2 command buttons. Change the captions on
    these to: Label1: SCOREBOARD Label2: LIONS Label3: SWANS Label4: 0 Label5: 0 Label6: Waiting for
    update... Command1: TOUCHDOWN Command2: TOUCHDOWN Once you are done, it shoud look like this.
    Press F5 now to see it in action. It won't do anything, seeing as how there is no path ....
  4. Installed Internet Explorer 7?, Visual Basic Now Broken?
    (3)
    This quick guide shows you how to fix this error. Step 1): Go to your control list by right
    clicking the toolbar underneat the default controls and clicking "Components" or by Pressing "CTRL +
    T". Step 2): In the Components Box that pops up scroll down to "Microsoft Internet Controls",
    click on it once so that it becomes highlighted. Now look at its "Location" it will say either
    "C:\Windows\System32\ieframe.dll" or "C:\Windows\System32\ieframe.dll\1". Step 3): Now you need to
    browse for the correct file, so with the "Microsoft Internet Control" still highlighted cli....
  5. [help] Visual Studio .net 2005 Questions
    (8)
    Heya folks, i am back again with my annoying questions /wink.gif" style="vertical-align:middle"
    emoid=";)" border="0" alt="wink.gif" /> I have this project to submit by the 7th of may and i am
    really desperate for some help here. I will put my questions in numbers so it would be easy for you
    to solve them without confusion. 1) Earlier in a post i had asked if i could create Vista
    compatible applications in VB .NET 2005. Well i got a good response and i went ahead and installed
    the needful, but i still think something is wrong. Not that i know alot of whats going on aro....
  6. Visual Basic Express Tutorials
    Need resources (5)
    I have just downloaded Microsoft Visual Basic Express 2005 and I need a tutorial to help me learn
    how to create simple programs. I have already watched the 16 hour RSS Reader series from Microsoft
    and I'm currently working on that. I also have developed a Web Browser and a weather tracker
    system, from the help of Microsoft E-Books and other Microsoft resources. If you could find any
    non-Microsoft resource on Visual Basic Express, that would be greatly appreciated.....
  7. Is There A Free IDE For VB.NET Programming?
    Needing info on a free VB.net IDE if avaliable (4)
    I know that VB.net is proprietry to Microsoft /sad.gif" style="vertical-align:middle" emoid=":("
    border="0" alt="sad.gif" /> but is there a free IDE that has all the support that VB.NET has? I
    found one before but it just didnt support many of the things that VB.NET does such as timers which
    was really annoying. Does anyone know of any IDEs like this that support the same functions and
    features as VB.NET but without the rather hefty (Over priced, in my opinion) price tag? If anyone
    does then drop me a PM or a reply! Thanks....
  8. Visual Basic.NET Help Needed.
    (8)
    I have a project to submit this wednesday, and i have to make it a working program. Not a big one ..
    but just sumthing small that includes : Splitter, Progress Bar & Track Bar. I thought of making
    sumthing like the picture below, I would enter the text and hit the button .. the text would come in
    BOTH the labels. Then i move the track bar on the left to increase the font or/and the track bar on
    the right to change the color ( RBG only 3 colors ). The progress bar at the bottom will show the
    progress every time i move either of the track bars to a level. Nothing fanc....
  9. New Features In Visual Studio 2005 Windows Forms
    (1)
    i dunno if all of u are by now well versed with the new exciting features in visual studio 2005
    forms, but for me this article was enlightening. for the benifit of others who wre in the dark like
    me.... New Features in Visual Studio 2005 Windows Forms QUOTE The little voice in my head
    shouted "Don't do it! Don't do it!" as I contemplated using the worn out cliché "Good things
    come to those who wait" to describe the experience of designing Windows applications with Visual
    Studio 2005. However, that cliché accurately communicates the idea that building Wi....
  10. Visual Basic Names
    Visual Basic Variabe Names (11)
    In Visual Basic, what is the difference between: ResourceName ResourceName$ ResourceName& ....
  11. Visual Basic 6 + Crystal Reports 9
    how to distribute (8)
    I have made a software with Visual Basic 6 and Crystal Reprots 9. Now I have to distribute it on the
    client side but the problem is coming in distributing the Crystal Reports. I have tried Setup
    Factory but it is not working. Then I have used Visual Studio Installer from Microsoft and
    downloaded Crystal Report Merge Modules from Business Objects website. It is working properly but
    now the setup file size is very big because it carries a lot of files with it. Is there any other
    installer software which can automatically select the required files to be distribute with the ....
  12. Visual Basic: Change Your Start Button Text! (XP)
    Windows XP ONLY (17)
    Personally, I love this program I made for myself. What the following code will allow you to do is
    change the text of your start button (Duh). You can make it whatever you want, your name, a hobby,
    or even do some extra programming and get it to randomly cycle through captions every 30 seconds or
    so /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />. Here is all
    the code you'll need: CODE Private Const WM_SETTEXT = &HC Private Const WM_GETTEXT = &HD
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpC....
  13. Visual Basic: Unload Your Application Correctly!
    (1)
    What many of us do not know is that using a button on a form with the function "Unload Form1" or
    even clicking the X in the upper right corner is like pulling the plug out of your computer while it
    is still on. It may not exit the program cleanly and efficiently, may leave background processes
    running, or just give you unwanted errors by exiting improperly. All you need to do is unload all
    components, forms, controls, etc. upon unloading. Say you have 2 forms in your project, 1
    component, and 2 controls. If these ojects are placed onto a form, unload them properly!....
  14. Visual Basic: Replace Explained!
    (6)
    This tutorial will go over how to effectively use the Replace function in Visual Basic. 1. So
    you have a string. Whether it be a label caption, an entry in a text box by the user of your
    program, or an item in a combo box. Let's say this is a bad string, something you do not want
    to appear. For instance, a user types "X is gay" in a text box, and you want to change that to
    something else. You can simply have it be deleted, or replaced with another value. 2. To make
    this work when a user types something in a textbox, you will need to use this sub: CODE ....
  15. Visual Basic.NET Through Movies
    (0)
    Hi all,     I found a very good site at MS which offers 101 short movie clips to strenghten various
    aspects of VB Programming and the IDE. Drastically cuts down on the learning curve. A very useful
    site for beginners: QUOTE Welcome to VB at the Movies. The 101 short films below will provide
    everybody from the beginner through the advanced developer with an opportunity to amp up their
    Visual Basic skills. Grab your popcorn and soda, sit back and enjoy! Source:
    http://msdn.microsoft.com/vbasic/atthemovies/default.aspx If you missed the link above, here it
    is a....
  16. Visual Basic Help
    need help useing visual basic (8)
    i was just wondering, when you are useing the program Visual Basic is there any way to add some
    animation to a form, and if so what is a good(cheep) animation program i could get?....
  17. [visual Basic] How To Confirm A Array Is Null
    (6)
    for example, Dim array() as integer during run time, how to confirm a array is null (do not
    contain any element) Thanks....
  18. Visual Basic - make Standard dlls in VB
    written entierly by me (1)
    if you want to know how to make dlls in visual basic, download my submission to
    planet-source-code.com: http://www.planet-source-code.com/vb/scrip...=54190&lngWId=1 Quoting
    what i said on the submission: QUOTE This code will allow you to make your very own stdcall DLL
    files using Visual Basic. The DLLs that you create can be called from any programming language that
    supports stdcall DLLs. Just create or open a project with the functions that you want to export,
    choose the functions to export and click compile! Create your own DLLs that you can call from any
    pro....

    1. Looking for visual, basic, random, strings

See Also,

*SIMILAR VIDEOS*
Searching Video's for visual, basic, random, strings
advertisement



Visual Basic: Random Strings!

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com