• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 359
  • Last Modified:

to display random questions from the total 50

Hello Experts,

I have 50 questions in the table and I am trying to show 30 random out of the total  on the web page using the following
  NextQuestion = ((50) * Rnd()) + 1
            While (is_Already_Answered(NextQuestion) = True)
                NextQuestion = ((50) * Rnd()) + 1
            End While

This works ok however, at times it is also assigning the number '51' to the NextQuestion. I also dont know whether it would consider the number '0' as well?

please advise

thanks
kay


0
learningnet
Asked:
learningnet
  • 6
  • 4
  • 3
  • +1
3 Solutions
 
ydramuCommented:
Why dont you use random.Next(51).

Which we generate random numbers from 1-50...and your code will work as expected.
0
 
learningnetAuthor Commented:
hello ydramu,
thanks for your comment

do you mean instead of using

NextQuestion = ((50) * Rnd()) + 1

use

NextQuestion = random.next(51)   ??

please advise as the above do not seems to have worked.

is random a built in function for vb ?

thanks for your help
0
 
ydramuCommented:
I got your point now. As the question is in ASP.NET category, I have given the VB.NET function.

Now to use the Random function in VB, we need to use Rnd() only.

To make the random function to work effectively, use the following formula..

Randomize()
upperbound = 50
lowerbound = 1
NextQuestion = CInt(Int((upperbound - lowerbound + 1) * Rnd() + lowerbound))

Before calling Rnd(), use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.

Please let me know if you have any questions.

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
learningnetAuthor Commented:
thanks for your amendments, this seems to have worked for me.

however, a slight problem, perhaps i am doing something wrong.

can you please let me know whether the statement below will get unique random numbers?

NextQuestion = CInt(Int((upperbound - lowerbound + 1) * Rnd() + lowerbound))

I mean, does this automatically picks up the unique numbers between 1 and 50 ?

For some reason, I am showing the same question twice on the page.

please advise
0
 
ydramuCommented:
The code will not generate random number by itself.

Your code now may become like this.

upperbound = 50
lowerbound = 1
While (is_Already_Answered(NextQuestion) = True)
     Randomize()
     NextQuestion = CInt(Int((upperbound - lowerbound + 1) * Rnd() + lowerbound))
End While

If I am not wrong, I expected the function you have is_Already_Answered(NextQuestion) will provide true, if it is a duplicate, isn't it?

0
 
Anurag ThakurCommented:
use this code sample
System.Random Rnd = new System.Random ();
 
ArrayList list = new ArrayList ();
for (int i = 0; i < 10; i++)
{
	int val = Rnd.Next (1, 50);
 
	if (list.Contains (val))
	{
		while (true)
		{
			val = Rnd.Next (1, 50);
			if (list.Contains (val) == false)
			{
				list.Add (val);
			}
		}
	}
	else
	{
		list.Add (val);
	}
}

Open in new window

0
 
learningnetAuthor Commented:
hello ydramu:
yes i am having a function which returns true if already already, i was thinking if i could get unique random numbers then i could remove that check
ragi0017:
thanks for your code sample, if i wanted to implement your code can i use something like this

  While (is_Already_Answered(NextQuestion) = True)
                NextQuestion = GetRandomQuestion()
            End While

can someone of you please advise?

thanks both for your help

    Protected Function GetRandomQuestion()
        Try
       Dim Rnd As New System.Random()
    
    Dim list As New ArrayList()
     For i As Integer = 0 To 9
         Dim val As Integer = Rnd.[Next](1, 50)
        
         If list.Contains(val) Then
             While True
                 val = Rnd.[Next](1, 50)
                 If list.Contains(val) = False Then
                   list.Add(val)
                End If
             End While
         Else
             list.Add(val)
         End If
     Next
 
 
        Catch ex As Exception
 
        End Try
 
        Return   list.Add(val)
    End Function

Open in new window

0
 
Anurag ThakurCommented:
hi we have jsut given you the logic on which you can build up as you please
i think (just looking at it) your logic also looks good
0
 
learningnetAuthor Commented:
ok thanks can you not please advise me how to implement this in my code?


ydramu:

please can you help me here?

thanks
0
 
learningnetAuthor Commented:
this still not returning unique random numbers

please advise
Protected Function GetRandomQuestion() As Integer
        Dim RetRandomNumber As Integer
        Try
            Dim Rnd As New System.Random()
 
            Dim list As New ArrayList()
            For i As Integer = 0 To 9
                Dim val As Integer = Rnd.[Next](1, 50)
 
                If list.Contains(val) Then
                    While True
                        val = Rnd.[Next](1, 50)
                        If list.Contains(val) = False Then
                            RetRandomNumber = val
                        End If
                    End While
                Else
                    RetRandomNumber = val
                End If
            Next
 
 
        Catch ex As Exception
 
        End Try
 
        Return RetRandomNumber
    End Function

Open in new window

0
 
ydramuCommented:
http://www.codetoad.com/vb_random.asp

Please have a look at this code. It has the logic to get the RandomNumber using Rnd() and then verifying whether it is duplicate or not.

0
 
Anurag ThakurCommented:
hi, if you use my coding logic are you not getting unique numbers?
0
 
learningnetAuthor Commented:
hello ydramu

It gave me an error saying object cannot be used as integer ... (please see attached)

NextQuestion = RandomNumbers(50, 1, 1)

ragi007,
yes it seems like its not doing it right, please see below
NextQuestion = GetRandomQuestion()
 Protected Function GetRandomQuestion() As Integer
        Dim RetRandomNumber As Integer
        Try
            Dim Rnd As New System.Random()

            Dim list As New ArrayList()
            For i As Integer = 0 To 9
                Dim val As Integer = Rnd.[Next](1, 50)

                If list.Contains(val) Then
                    While True
                        val = Rnd.[Next](1, 50)
                        If list.Contains(val) = False Then
                            RetRandomNumber = val
                        End If
                    End While
                Else
                    RetRandomNumber = val
                End If
            Next


        Catch ex As Exception

        End Try

        Return RetRandomNumber
    End Function
 Public Function RandomNumbers(ByVal Upper As Integer, _
    Optional ByVal Lower As Integer = 1, _
    Optional ByVal HowMany As Integer = 1, _
    Optional ByVal Unique As Boolean = True) As Object
        '*******************************************************
        'This Function generates random array of 
        'Numbers between Lower & Upper
        'In Addition parameters can include whether 
        'UNIQUE values are required
 
        'Note the Result is INCLUSIVE of the Range
 
        'Debug Example:
        'x = RandomNumbers(49, 1, 7)
        'For n = LBound(x) To UBound(x): Debug.Print x(n);: Next n
        'WARNING HowMany MUST be greater than (Higher - Lower)
        '******************************************************
 
        On Error GoTo LocalError
        If HowMany > ((Upper + 1) - (Lower - 1)) Then Exit Function
        Dim x As Integer
        Dim n As Integer
        Dim arrNums() As Object
        Dim colNumbers As New Collection
 
        ReDim arrNums(HowMany - 1)
        With colNumbers
            'First populate the collection
            For x = Lower To Upper
                .Add(x)
            Next x
            For x = 0 To HowMany - 1
                n = RandomNumber(0, colNumbers.Count + 1)
                arrNums(x) = colNumbers(n)
                If Unique Then
                    colNumbers.Remove(n)
                End If
            Next x
        End With
        colNumbers = Nothing
        RandomNumbers = arrNums
        Exit Function
LocalError:
        'Justin (just in case)
        RandomNumbers = ""
    End Function
 
 
    Public Function RandomNumber(ByVal Upper As Integer, _
    ByVal Lower As Integer) As Integer
        'Generates a Random Number BETWEEN the LOWER and UPPER values
        Randomize()
        RandomNumber = Int((Upper - Lower + 1) * Rnd + Lower)
    End Function

Open in new window

0
 
hieloCommented:
>>I have 50 questions in the table and I am trying to show 30 random out of the total
Not sure what db you are using but did you try just selecting 30 random records directly from the db instead of saving the records to some array and then selecting random records from your array. If your query generates 30 random records directly you would just use the records directly from the recordset. Ex:

select top 30 columns....
    from table
    order by newid()
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 6
  • 4
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now