Jump to content
xisto Community
Sign in to follow this  
eina

Random Questions In Vb.. pls help..

Recommended Posts

hello is there anyone here know how to create a code for a 10 random questions out of 100 using Visual Basic?That a set of ten questions will be displayed randomly?Thanks in advance

Share this post


Link to post
Share on other sites

This is so simple I almost have to wonder if it's not a home work question of some sort. Simply put all the questions (enumerated) into a data store of some sort be it a database an xml file or even a text file. Connect to the data and use VB to randomly select a question then repeat nine times.

Share this post


Link to post
Share on other sites

This is so simple I almost have to wonder if it's not a home work question of some sort.
Simply put all the questions (enumerated) into a data store of some sort be it a database an xml file or even a text file. Connect to the data and use VB to randomly select a question then repeat nine times.


it is my project in school.

we are not allowed to use database.

can you please give me a sample code how to do this? am a newbie.
Edited by eina (see edit history)

Share this post


Link to post
Share on other sites

This actually might be a tad harder than what Darasen suggests. The biggest problem is selecting mutual exclusive questions, i.e. not selecting the same question twice. Even though this is a homework question I will still provide some code. The bottom line is that blindly copying someone elseâs work without understanding it is stupid and you will do poorly in your class. On the other hand I donât think stupid should be illegal so here it is.

This project is created in Visual Studio Express 2008 and is part of a program that I offer called YCC Yahoo! Bot Maker (http://forums.xisto.com/no_longer_exists/). YCC Yahoo! Bot Maker is simply a front end for making Yahoo! IDs and it requires input from the user to select such things as birthday and a security question. One of the options in Bot Maker is the ability to fill in random user data similar to picking 10 questions out of 100. This example will focus on the security question.

The original program only has to pick one question so as a demonstration I will also pick a second question and show the results. The project goes onto a form called frmMain with two TextBoxes (txtQuestion1, txtQuestion2) and a Button named btnGenerate. The main function is the event handler for the Generate button. There are two random functions but one is just a call to the other more general function and the last function is what holds the questions in the form of a Case statement.

The first question is straight forward and you just enter a random question for the security question list. The second question is more complicated because you canât have the same question twice. As I generate the first question I enter it into a Collection and hold it for future reference. The second question is in a While loop and will compare the random question with what is already in the collection to see if it already exists. If it is unique then the While loop variable is set to True and the loop breaks. Since there are very few security questions, you will encounter a duplicate question very often.

As you can see this is not exactly the same that you requested but it should get you going in the proper direction. My solution is not very elegant but it gets the job done. When adding addition questions I would suggest adding a global variable that sets the number of questions to ask. From this you may be able to do some sort of For loop to iterate through all of the questions. The Collection is already setup for addition questions and thatâs why I choose it over a Boolean or string. If you are studying arrays then you may want to opt for that instead of a Collection but I prefer the Collection because it already has many features built-in.

Option Strict OnOption Explicit OnPublic Class frmMain	Private Sub btnGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerate.Click		Dim cExistingQuestions As New Collection		Dim bValidQuestion As Boolean = False		txtQuestion1.Text = randomPWQuestion(randomNumber(0, 8))		cExistingQuestions.Add(txtQuestion1.Text, txtQuestion1.Text)		While bValidQuestion = False			Dim strQuestion2 As String = randomPWQuestion(randomNumber(0, 8))			If cExistingQuestions.Contains(strQuestion2) Then				bValidQuestion = False			Else				bValidQuestion = True				txtQuestion2.Text = strQuestion2			End If		End While	End Sub	Private Function generateRandom(ByVal iLowerBound As Integer, ByVal iUpperBound As Integer) As Integer		Randomize()		Dim r As New Random		Return r.Next(iLowerBound, iUpperBound)	End Function	Public Function randomNumber(ByVal iLower As Integer, ByVal iUpper As Integer) As Integer		Return generateRandom(iLower, iUpper)	End Function	Private Function randomPWQuestion(ByVal iRandom As Integer) As String		Select Case iRandom			Case 0				Return "Where did you meet your spouse?"			Case 1				Return "What was the name of your first school?"			Case 2				Return "Who was your childhood hero?"			Case 3				Return "What is your favorite pastime?"			Case 4				Return "What is your favorite sports team?"			Case 5				Return "What is your father's middle name?"			Case 6				Return "What was your high school mascot?"			Case 7				Return "What make was your first car or bike?"			Case 8				Return "What is your pet's name?"		End Select		Return "Where did you meet your spouse?"	End FunctionEnd Class

Edited by tansqrx (see edit history)

Share this post


Link to post
Share on other sites

It looks like Iâm just a sucker for bleeding heart cases. I just took a smoke break and I came up with a better solution than the previous one. The best way to do this is to create an array and allocate all of the questions before hand. The array will be filled with numbers that are mutually exclusive.

Since I am such a sucker I also figured out the way to best display the questions. I added a FlowLayoutPanel and then add a label control programmatically for each of the answers.

Once again this may not be the best or most efficient solution but it gets the job done along with a nice user interface. I have attached the VB.NET project along with the reply if you would like to see how it works.



Option Strict OnOption Explicit OnPublic Class frmMain	Private _iQuestionCount As Integer	Private Sub btnGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerate.Click		_iQuestionCount = CInt(nudQuestionCount.Value)		Dim iIndex As Integer		Dim iRandomValue As Integer		Dim bValidQuestion As Boolean = False		Dim aQuestions(_iQuestionCount - 1) As Integer		'set all the elements to -1 because the default 0 was tripping up the serach function.		For iIndex = 0 To _iQuestionCount - 1			aQuestions(iIndex) = -1		Next		For iIndex = 0 To _iQuestionCount - 1			While bValidQuestion = False				iRandomValue = randomNumber(0, 8)				If SearchArray(aQuestions, iRandomValue) = True Then					bValidQuestion = False				Else					bValidQuestion = True					aQuestions(iIndex) = iRandomValue				End If			End While			bValidQuestion = False		Next		'populate the questions to the form		'clear the form if needed		flpMain.Controls.Clear()		For iIndex = 0 To aQuestions.Length - 1			Dim lQuestion As New Label			lQuestion.Size = New System.Drawing.Size(485, 13)			lQuestion.Text = "(" + CStr(aQuestions(iIndex)) + ") " + randomPWQuestion(aQuestions(iIndex))			flpMain.Controls.Add(lQuestion)		Next	End Sub	Private Function SearchArray(ByVal aArray As Array, ByVal iValue As Integer) As Boolean		Dim iArrayValue As Integer		For Each iArrayValue In aArray			If iArrayValue = iValue Then				Return True			End If		Next		Return False	End Function	Private Function generateRandom(ByVal iLowerBound As Integer, ByVal iUpperBound As Integer) As Integer		Randomize()		Dim r As New Random		Return r.Next(iLowerBound, iUpperBound)	End Function	Public Function randomNumber(ByVal iLower As Integer, ByVal iUpper As Integer) As Integer		Return generateRandom(iLower, iUpper)	End Function	Private Function randomPWQuestion(ByVal iRandom As Integer) As String		Select Case iRandom			Case 0				Return "Where did you meet your spouse?"			Case 1				Return "What was the name of your first school?"			Case 2				Return "Who was your childhood hero?"			Case 3				Return "What is your favorite pastime?"			Case 4				Return "What is your favorite sports team?"			Case 5				Return "What is your father's middle name?"			Case 6				Return "What was your high school mascot?"			Case 7				Return "What make was your first car or bike?"			Case 8				Return "What is your pet's name?"		End Select		Return "Where did you meet your spouse?"	End FunctionEnd Class

Share this post


Link to post
Share on other sites

This actually might be a tad harder than what Darasen suggests. The biggest problem is selecting mutual exclusive questions, i.e. not selecting the same question twice.

Not too hard really. How I would do it actually would be to have all the questions in simple text delimited file. Bear in mind I have no idea if this was allowed for the problem indicated by the OP but it is inconsequential. I would not use a commas for separators as they may be needed to make the questions grammatically correct. The separate file would make modifying adding or subtracting questions far easier in the future as well.

Next use ADO to connect to the text file. In ADO you can write an SQL query that selects a certain amount of rows at random.
This example Comes from a HeroScape random army creator that I programmed in Access. The query will randomly select 10 unique records.

SELECT TOP 10 *FROM tbl_listORDER BY RND(ID);

This exact query may not work through the ADO connection and the MS text driver but, I feel fairly certain that the correct syntax shouldn't be too hard to work out. That is just how I would it with out putting too much thought (or code) into it.

Share this post


Link to post
Share on other sites

I agree with Darasen that its quite easy. My technique would be without using ADO, though and it would need some custom classes to be written if you are using Visual Basic 6.0 or lower.

 

Basically there are two steps in selecting mutually exclusive options. First, we need to select a question from the list by generating a random number between 1 to 100. For VB .NET, you use the Random class to do this.

 

Dim Rnd As Random = new Random()Dim Index as Integer = Rnd.Next(1, 101)

Note: The second parameter to the Next method of the Random class must be one higher than the upper bound.

 

For Visual Basic, use the Rnd function and the following formula to generate a random number between LowestValue & HighestValue.

 

Int((HighestValue - LowestValue + 1) * Rnd) + LowestValue

 

Dim Index as IntegerIndex = Int((100 - 1 + 1) * Rnd) + 1

Store the random number in a variable and retrieve the element at that index from the list of questions. (Bear in mind that VB .NET arrays are zero based).

 

For VB .NET:-

 

Dim Questions As New List(Of String)()' Add the 100 questions to the list here Questions.Add("What beath your name?")Questions.Add("How young are you?")' --' Retrieve the question at position IndexDim MyQuestion As String = Questions(Index - 1)

Now that the question has been selected, you must remove it from the list.

 

Questions.RemoveAt(Index)

Repeat these steps to once again generate a random index, select an element at that index & finally remove that index from the list. Only this time, you need to generate the number in between 1 & 99.

 

For VB 6 you need to write a class equivalent to .NET's List class which will allow you to add/remove elements at any position in the list.

Edited by turbopowerdmaxsteel (see edit history)

Share this post


Link to post
Share on other sites

Turbopoweredmaxsteel has a fine alternative method. I didn’t even think about adding everything to a list and then decrementing the random variable. I actually think this would be the most efficient (fastest) way to go for most applications. One small area where my approach may be more efficient is if you have some extremely long questions and there is a high penalty for I/O or the question list is more like 1 million questions and not 100. In this case loading all of the questions would be compute expensive and take up a lot of memory.

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
Sign in to follow this  

×
×
  • 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.