Random without repeating vb.Net

I am trying to make a little quiz program that randomize from an array of 20 questions to get 5 random questions without repeating any of them I've searched and found that i need to use "Static" but it didn't Work I also tried System.Random() but it always repeat the same questions I also need an initial question on the form load and the others when the submit button is clicked so they can't overlap too any help ?

Upvotes: 1

Views: 866

Answers (2)

Here is my try to avoid duplicates but it didn't work this code is supposed to pick a random value from "pick" List and then remove that value from the list

Dim ind As New List(Of Integer)
 Dim pick As New List(Of Integer)

For j = 0 To 13
            pick.Add(j)
        Next
        Dim randomvalue As Random = New System.Random
        Randomize()
        For j = 0 To 6
            Dim val = randomvalue.Next(pick(pick.Count - 1))
            ind.Add(val)
            pick.Remove(val)
        Next

Upvotes: 0

David
David

Reputation: 6111

You don't want random numbers, but rather a range of numbers that are randomly ordered.

Assuming that your questions are simply stored in a String array, you can use LINQ's OrderBy to randomly order the numbers 1-20, and then get the first 5 numbers after the order has been randomized by using LINQ's Take.

Take a look at this example:

Dim indices() As Integer = Enumerable.Range(0, questions.Length - 1).OrderBy(Function(i) r.Next()).Take(5).ToArray()

Fiddle: Live Demo

Upvotes: 1

Related Questions