Randomise()
Dim questions(14) as string
Dim picked questions(4) as string
Dim rand as new random
Questions(0) = "?"
Questions(1) = "?"
...
Questions(14) = "?"
For counter = 0 to 4
Pickedquestions(counter) = questions(rand.next(0,15))
Next
我有一系列问题,我想从这一组中挑选5个问题。然而,我的方法意味着一些挑选的问题与我想避免的相同。我被建议使用排序算法对数组进行随机排序,然后选择第一个5.问题是我是初学者,我不明白如何将其合并到我的代码中。任何帮助或其他建议将不胜感激,谢谢。
答案 0 :(得分:1)
这是来自here的Jon Skeet' s Shuffle()的VB.Net版本:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static rnd As New Random
Dim questions(14) As String
' ...
Dim PickedQuestions = questions.Shuffle(rnd).Take(4).ToArray()
For i As Integer = 0 To PickedQuestions.Length - 1
Debug.Print("PickedQuestions(" & i & ") = " & PickedQuestions(i))
Next
End Sub
End Class
Module Module1
' VB.Net Conversion of Jon Skeet's Shuffle() from: https://stackoverflow.com/a/1287572/2330053
<System.Runtime.CompilerServices.Extension> _
Public Iterator Function Shuffle(Of T)(source As IEnumerable(Of T), rng As Random) As IEnumerable(Of T)
Dim elements As T() = source.ToArray()
For i As Integer = elements.Length - 1 To 0 Step -1
Dim swapIndex As Integer = rng.Next(i + 1)
Yield elements(swapIndex)
elements(swapIndex) = elements(i)
Next
End Function
End Module
好的......这里的东西多了一点......简单&#34;:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static rnd As New Random
Dim questions(14) As String
For i As Integer = 0 To questions.Count - 1
questions(i) = "Question " & i
Next
Dim tmpQuestions As New List(Of String)(questions)
Dim PickedQuestions As New List(Of String)
For i As Integer = 1 To 4
Dim index As Integer = rnd.Next(tmpQuestions.Count)
PickedQuestions.Add(tmpQuestions(index))
tmpQuestions.RemoveAt(index)
Next
For i As Integer = 0 To PickedQuestions.Count - 1
Debug.Print(i & ": " & PickedQuestions(i))
Next
End Sub
答案 1 :(得分:0)
随机播放questions
数组并获取前四项。只需要一点Linq就可以了。
Imports System
Imports System.Linq
...
Dim questions(14) as string
...
Dim rnd As New Random
Dim PickedQuestions = questions.OrderBy(Function() rnd.Next).Take(4).ToArray()
虽然简单而且相当直接,正如 Joel 所指出的那样,这不是最佳方法(但可能足以满足您的目的)。有关更好的排序算法,请参阅John Skeet's answer here。