Shuffling an array of strings in vb.net

I am developing a web page in vb.net that will generate the user several questions with several choices. I need to shuffle four answers that are already placed in an array. Suppose I have the following array:

array = {"Correct", "Wrong1", "Wrong2", "Wrong3"}

I tried using the following method:

Public Shared Function Shuffle(ByVal items() As String) As Array
        Dim max_index As Integer = items.Length - 1
        Dim rnd As New Random(DateTime.Now.Millisecond)
        For i As Integer = 0 To max_index
            ' Pick an item for position i.
            Randomize()
            Dim j As Integer = rnd.Next(i, max_index)
            ' Swap them.
            Dim temp As String = items(i)
            items(i) = items(j)
            items(j) = temp
        Next i
        Return items
    End Function

The function works very well, but my problem is that if I have four questions, the answers will be shuffled for each question, but the correct answer will be in one position:

    array = {"Wrong1", "Correct", "Wrong2", "Wrong3"}
    array = {"Wrong2", "Correct", "Wrong3", "Wrong1"}
    array = {"Wrong3", "Correct", "Wrong1", "Wrong2"}
    array = {"Wrong1", "Correct", "Wrong3", "Wrong2"}

I need the right answer to change my location from one question to another. Your help is appreciated.

+2
source share
1 answer

Shuffle Random.

  • Randomize , VB Rnd. NET Random.
  • ; .
  • Random , , ( -). - .

  • Random.Next(min, max) , 1 , .

  • Shuffle , :

Fisher-Yates:

' form/class level var
Private rnd As New Random()

Public Sub Shuffle(items As String())
    Dim j As Int32
    Dim temp As String

    For n As Int32 = items.Length - 1 To 0 Step -1
        j = rnd.Next(0, n + 1)
        ' Swap them.
        temp = items(n)
        items(n) = items(j)
        items(j) = temp
    Next i
End Sub

4 :

Shuffle #1    Wrong3   Correct  Wrong2   Wrong1   
Shuffle #2    Correct  Wrong2   Wrong1    Wrong3   
Shuffle #3    Wrong2   Correct  Wrong3    Wrong1   
Shuffle #4    Correct  Wrong1   Wrong2    Wrong3   
Shuffle #5    Correct  Wrong1   Wrong3    Wrong2   

Random ( ):

Public Sub Shuffle(items As String(), RNG As Random)

:

' Generic shuffle for basic type arrays
Public Sub Shuffle(Of T)(items As T(), rng As Random)
    Dim temp As T
    Dim j As Int32

    For i As Int32 = items.Count - 1 To 0 Step -1
        ' Pick an item for position i.
        j = rng.Next(i + 1)
        ' Swap 
        temp = items(i)
        items(i) = items(j)
        items(j) = temp
    Next i
End Sub

:

Shuffle(intArray, myRnd)
Shuffle(strArray, myRnd)
Shuffle(colors, myRnd)
Shuffle(myButtons, myRnd)

, - , , :

Dim ShuffledItems = myItems.OrderBy(Function() rnd.Next).ToArray()

, .

1 , , - . "X" items(j) , , rnd.Next(0, n + 1) /. .

+5

Source: https://habr.com/ru/post/1626795/


All Articles