none
How to perform randomization in VB.net?

    Question

  • I am developing a Quiz project using VB.net and Access 2003 database(IDE: Visual studio 2015). I have almost developed the project and it is working correctly. Now I need questions to be picked up randomly from the question paper, with options randomised as well i.e. same person logging in again or different person sitting next to you should not get same questions or same options for same question.

    So I don't know how to perform this randomization. Can anyone please guide me and provide me a idea for performing this task.

    Thank you in advance

    Friday, March 17, 2017 7:38 PM

Answers

  • Thank you for your response sir!!!!

    It would be great helpful if you write a simple code for performing the above task. I have never used List(OfYourClass) before so don't know its necessary methods to perform randomization task.


    So please just write a simple code regarding your above explanation. Then I can understand it and implement in my project.


    Waiting for your response.

    Thank you

    I presume that you're talking to me? We don't all see this forum the same way so please make it obvious.

    *****

    I agree with Acamar that there's not enough to go on to get very specific, but I can show you the concept that you can duplicate:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Public Class Form1
        Private rand As Random
    
    
    
        Private Sub Form1_Load(ByVal sender As System.Object, _
                               ByVal e As System.EventArgs) _
                               Handles MyBase.Load
    
            rand = New Random
            DemonstrateRandom()
    
        End Sub
    
    
    
        Private Sub DemonstrateRandom()
    
            Dim tempList As New List(Of String) _
                From {"The", "Quick", "Brown", "Fox", _
                 "Jumps", "Over", "The", "Lazy", "Dog"}
    
            Dim sb As New System.Text.StringBuilder
    
            Do While tempList.Count > 0
                Dim idx As Integer = rand.Next(0, tempList.Count)
                sb.AppendLine(tempList(idx))
                tempList.RemoveAt(idx)
            Loop
    
            MessageBox.Show(sb.ToString)
    
        End Sub
    End Class


    Run that a few times and you might even want to put a breakpoint in and step into each line of code as it runs. I think that will give you a good idea of what's going on, better than anything, but here are a few things:

    First, the list that I meant is a generic list:

    https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

    The List(Of Class) isn't used in the example above but I am using a List(Of String) so that I can freely remove elements from it.

    I start a loop that will continue until the list is empty.

    On each loop, it gets a random index number based on a minimum of 0 and a maximum of whatever the count of the list is at that point in time. The .Next method is a bit odd in that the minimum is inclusive but the maximum is exclusive, so that's why I'm doing it that way.

    Using that index, I grab the string that's in the list at that index, add that to a StringBuilder (which is scoped outside the loop), then remove the string at that index.

    Lastly, please note that I create a NEW instance of the random only once. That keeps it from creating duplicate patterns:

    "The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated."

    (Ref: https://msdn.microsoft.com/en-us/library/system.random(v=vs.100).aspx)

    Make sense?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    • Proposed as answer by Cor LigthertMVP Saturday, March 18, 2017 1:57 PM
    • Marked as answer by Tabzee Monday, March 20, 2017 4:33 AM
    Saturday, March 18, 2017 8:41 AM

All replies

  • I am developing a Quiz project using VB.net and Access 2003 database(IDE: Visual studio 2015). I have almost developed the project and it is working correctly. Now I need questions to be picked up randomly from the question paper, with options randomised as well i.e. same person logging in again or different person sitting next to you should not get same questions or same options for same question.

    So I don't know how to perform this randomization. Can anyone please guide me and provide me a idea for performing this task.

    Thank you in advance

    Unless it's an incredibly large amount of data, create a class, load the data from your data store into instances of that class, then you can use the Random class to generate a random number.

    With regard to what to do, create a collection (like a List(Of YourClass)) and use the Next method to generate a random number based on 0 as the minimum and the count of the collection as the maximum.

    After the random number is generated, select the instance from your collection at that index from your collection, return that instance of the class from your collection, then remove it from your collection (so that it can't be chosen again).


    "A problem well stated is a problem half solved.” - Charles F. Kettering


    Friday, March 17, 2017 8:00 PM
  • You might also just get a copy of your item collection in a random order and then iterate over the randomized collection.

    Private Function GetRandomOrder(Of T)(collection As IEnumerable(Of T)) As IEnumerable(Of T)
        Dim r As New Random
        Return (From item In collection Order By r.Next).ToArray
    End Function
    

    Dim items = {1, 2, 3, 4, 5, 6, 7, 8, 9}
    For Each randomItem In GetRandomOrder(items)
        Debug.Print(randomItem.ToString)
    Next
    


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Friday, March 17, 2017 11:30 PM
    Moderator
  • Thank you for your response sir!!!!

    It would be great helpful if you write a simple code for performing the above task. I have never used List(OfYourClass) before so don't know its necessary methods to perform randomization task.

    So please just write a simple code regarding your above explanation. Then I can understand it and implement in my project.

    Waiting for your response.

    Thank you

    Saturday, March 18, 2017 6:34 AM
  • It would be great helpful if you write a simple code for performing the above task.

    If you require an example you will need to provide more details.

    "I need questions to be picked up randomly from the question paper".  What is a 'question paper' and what is a 'question'?   To provide an example of picking something at random, you will need to show what it is that the pick process needs to pick from.   For example, if you asked each question in sequence from first to last, how would you do the picking?  That's the process that needs to be made random.

    "options randomised as well".  Same requirement.  What is an 'option', and how do you pick one option in your existing code?   If you show how one gets picked, it should be possible to show how that picking could be made random.

    Saturday, March 18, 2017 6:42 AM
  • Thank you for your response sir!!!!

    It would be great helpful if you write a simple code for performing the above task. I have never used List(OfYourClass) before so don't know its necessary methods to perform randomization task.


    So please just write a simple code regarding your above explanation. Then I can understand it and implement in my project.


    Waiting for your response.

    Thank you

    I presume that you're talking to me? We don't all see this forum the same way so please make it obvious.

    *****

    I agree with Acamar that there's not enough to go on to get very specific, but I can show you the concept that you can duplicate:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Public Class Form1
        Private rand As Random
    
    
    
        Private Sub Form1_Load(ByVal sender As System.Object, _
                               ByVal e As System.EventArgs) _
                               Handles MyBase.Load
    
            rand = New Random
            DemonstrateRandom()
    
        End Sub
    
    
    
        Private Sub DemonstrateRandom()
    
            Dim tempList As New List(Of String) _
                From {"The", "Quick", "Brown", "Fox", _
                 "Jumps", "Over", "The", "Lazy", "Dog"}
    
            Dim sb As New System.Text.StringBuilder
    
            Do While tempList.Count > 0
                Dim idx As Integer = rand.Next(0, tempList.Count)
                sb.AppendLine(tempList(idx))
                tempList.RemoveAt(idx)
            Loop
    
            MessageBox.Show(sb.ToString)
    
        End Sub
    End Class


    Run that a few times and you might even want to put a breakpoint in and step into each line of code as it runs. I think that will give you a good idea of what's going on, better than anything, but here are a few things:

    First, the list that I meant is a generic list:

    https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

    The List(Of Class) isn't used in the example above but I am using a List(Of String) so that I can freely remove elements from it.

    I start a loop that will continue until the list is empty.

    On each loop, it gets a random index number based on a minimum of 0 and a maximum of whatever the count of the list is at that point in time. The .Next method is a bit odd in that the minimum is inclusive but the maximum is exclusive, so that's why I'm doing it that way.

    Using that index, I grab the string that's in the list at that index, add that to a StringBuilder (which is scoped outside the loop), then remove the string at that index.

    Lastly, please note that I create a NEW instance of the random only once. That keeps it from creating duplicate patterns:

    "The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated."

    (Ref: https://msdn.microsoft.com/en-us/library/system.random(v=vs.100).aspx)

    Make sense?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    • Proposed as answer by Cor LigthertMVP Saturday, March 18, 2017 1:57 PM
    • Marked as answer by Tabzee Monday, March 20, 2017 4:33 AM
    Saturday, March 18, 2017 8:41 AM
  • Thank you for your response sir!!!!

    It would be great helpful if you write a simple code for performing the above task. I have never used List(OfYourClass) before so don't know its necessary methods to perform randomization task.

    So please just write a simple code regarding your above explanation. Then I can understand it and implement in my project.

    Waiting for your response.

    Thank you

    Through all of this, I'm assuming this is a multiple-choice quiz. If it's not then please explain that.

    *****

    As far as the List(Of Class), you need to first come up with the class.

    In the following, by encapsulating the prospective answer along with a boolean to indicate whether or not it's the correct answer, you can have as many potential answers as you want:

    Public Class QuizData
        Private _question As String
        Private _answers As IEnumerable(Of Answer)

        Public Sub New(ByVal questionText As String, _
                       ByVal ParamArray answers() As Answer)

            If Not String.IsNullOrWhiteSpace(questionText) AndAlso _
                answers.Length > 0 Then

                _question = questionText.Trim
                _answers = answers
            End If

        End Sub

        Public ReadOnly Property Answers As IEnumerable(Of Answer)
            Get
                Return _answers
            End Get
        End Property

        Public ReadOnly Property Question As String
            Get
                Return _question
            End Get
        End Property

        Public Overrides Function ToString() As String

            Dim sb As New System.Text.StringBuilder

            sb.AppendLine(_question)

            For Each ans As Answer In _answers
                If ans.IsCorrect Then
                    sb.AppendLine(String.Format("{0} (Correct Answer)", ans.Text))
                Else
                    sb.AppendLine(ans.Text)
                End If
            Next

            sb.Remove(sb.Length - 2, 2)

            Return sb.ToString

        End Function
    End Class





    Public Class Answer
        Private _text As String
        Private _isCorrect As Boolean

        Public Sub New(ByVal text As String, _
                       Optional ByVal isCorrect As Boolean = False)

            If Not String.IsNullOrWhiteSpace(text) Then
                _text = text.Trim
                _isCorrect = isCorrect
            End If

        End Sub

        Public ReadOnly Property IsCorrect As Boolean
            Get
                Return _isCorrect
            End Get
        End Property

        Public ReadOnly Property Text As String
            Get
                Return _text
            End Get
        End Property
    End Class


    With that you might now create a List(Of QuizData) and then proceed to put information in it:

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private _quizList As List(Of QuizData) Private Sub Form1_Load(sender As System.Object, _ e As System.EventArgs) _ Handles MyBase.Load PopulateQuiz() Stop End Sub Private Sub PopulateQuiz() _quizList = New List(Of QuizData) With _quizList .Add(New QuizData("The chief distinguishing feature of psychotic disorders is", _ New Answer("antisocial conduct."), _ New Answer("confusion of fantasy and reality.", True), _ New Answer("overwhelming anxiety."), _ New Answer("obsessive behavior."))) .Add(New QuizData("A common form of mental disorder afflicting 10-20% of the population is", _ New Answer("schizophrenia."), _ New Answer("senile dementia."), _ New Answer("depression.", True), _ New Answer("delusional disorder."))) .Add(New QuizData("Bob has never met Madonna but he is convinced that she is deeply in love with him. Bob is suffering from", _ New Answer("grandiose delusions.", True), _ New Answer("jealous delusions."), _ New Answer("obsessive-compulsive disorder."), _ New Answer("rotomanic delusions."))) .Add(New QuizData("A much-feared outcome of Alzheimer's disease is", _ New Answer("functional psychosis."), _ New Answer("paranoia."), _ New Answer("general paresis."), _ New Answer("senile dementia.", True))) End With End Sub End Class


    At "Stop", hover your mouse over the class-scoped variable named "_quizList" and you'll see the data:

    I hope that gives you some ideas. :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering


    • Edited by Frank L. Smith Saturday, March 18, 2017 10:17 AM ... I left out the second class
    Saturday, March 18, 2017 10:12 AM
  • It would be great helpful if you write a simple code for performing the above task.

    If you require an example you will need to provide more details.

    "I need questions to be picked up randomly from the question paper".  What is a 'question paper' and what is a 'question'?   To provide an example of picking something at random, you will need to show what it is that the pick process needs to pick from.   For example, if you asked each question in sequence from first to last, how would you do the picking?  That's the process that needs to be made random.

    "options randomised as well".  Same requirement.  What is an 'option', and how do you pick one option in your existing code?   If you show how one gets picked, it should be possible to show how that picking could be made random.

    Thank you for your response sir!!!

    I will provide you more details regarding my project.

    In my database there are many Questions papers, and admin selects a question paper during test(for the student) and also enters maximum limit of questions from that paper for the test.

    The question paper has 6 columns,

    1)Question (Question entered will be save here)

    2)Option A

    3)Option B

    4)Option C

    5)Option D

    6)Answer (Here the selected answer among the 4 options will be saved)

    During the test I want the questions to be selected randomly from the Question papers. For example : There are 10 questions stored in the Question paper, and during test admin entered the max limit as 5.Then 5 questions should be chosen randomly among 10 questions and also the options of particular questions should be randomized(shuffled among 4 options) and displayed during the test.

    Hope this gave you a brief view of the pick process.

    Please give me an example code for above solution.

    Waiting for your response!!!

    Thank you in advance sir

    Saturday, March 18, 2017 1:03 PM
  • Tabzee,

    Did you read/try any of what I posted?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, March 18, 2017 1:21 PM
  • In my database there are many Questions papers, and admin selects a question paper during test(for the student)

    Show the code that does this.

    Your random selection will start with a number.  So you have to convert that random number into a selection.  For instance, if the question paper is selected using a database query that uses a question paper ID, then you might create the ID as a random value by concatenating a random number to a name. 

    Or, you might create a table of question records and select one question from the rows in the table using a random row number.   

    Dim RND As New Random()
    ...
      Dim row As DataRow = dt.Rows(RND.Next(dt.Rows.Count))
    
    

    Saturday, March 18, 2017 8:54 PM
  • Tabzee,

    Did you read/try any of what I posted?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Yes sir I read. I did not understood entire code of class, But your second answer really helped me to understand the concept.

    Thank you

    Monday, March 20, 2017 4:32 AM

  • Yes sir I read. I did not understood entire code of class, But your second answer really helped me to understand the concept.

    Thank you

    I'm glad it helped. :)

    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Monday, March 20, 2017 11:45 AM


  • I'm glad it helped. :)

    Yes sir I successfully implemented in my project and it is working correctly.

    Once again Thanks a lot:)

    Monday, March 20, 2017 3:34 PM
  • Yes sir I successfully implemented in my project and it is working correctly.

    Once again Thanks a lot:)

    :-)

    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Monday, March 20, 2017 3:36 PM