有时候,您只是知道您会因为某个问题而被枪杀,但此事无济于事。
我有一个二维数组的字符串,名为Questions,是的测验。而且,如果不将原始的“问题”数组类型更改为更简单的结构列表(如结构列表),是否有一种更优雅的方式来改变问题的顺序?
这就是我所拥有的:
'1st I create 3 arrays to hold the 3 components of each Question
Dim arrQ((Questions.Length / 4) - 1) As String 'question
Dim arrA((Questions.Length / 4) - 1) As String 'answer
Dim arrM((Questions.Length / 4) - 1) As String 'media name
'2nd I copy the values from question array into individual arrays
Dim z As Integer
For z = 0 To (Questions.Length / 4) - 1
arrQ(z) = Questions(0, z)
arrA(z) = Questions(1, z)
arrM(z) = Questions(2, z)
Next
'create an array to hold our shuffled questions
Dim x As Integer
Dim randarray(total_quizquestions - 1) As Integer
'create a list that we can remove index once they've been added to randarray
Dim list As New ArrayList
For i As Integer = 0 To total_quizquestions - 1
list.Add(i)
Next i
'add and remove
Dim rand As New Random
Dim index As Integer
For x = 0 To total_quizquestions - 1
index = rand.Next(0, list.Count)
randarray(x) = list(index)
list.RemoveAt(index)
Next
'clear original Questions
ReDim Preserve Questions(3, total_quizquestions - 1)
'add back to questions using randarray random number to get rows from arrQ etc.
Dim f As Integer = 0
For f = 0 To total_quizquestions - 1
Questions(0, f) = arrQ(randarray(f))
Questions(1, f) = arrA(randarray(f))
Questions(2, f) = arrM(randarray(f))
Next f
嘿,请问,我的代码可以用,但是太丑了,我感到羞愧!哦,是的,问题的确包含4个元素,但我只对前3个感兴趣。 善待...
答案 0 :(得分:2)
LINQ在2D数组上不能很好地发挥作用,因此您对不更改基本数组的结构的要求排除了许多不错的,优雅的解决方案。
话虽如此,您可以使用Fisher-Yates shuffle algorithm来就地随机化数组。
此代码基于我在上一段中链接到的答案(贷记给Nat Pongjardenlarp)。我已经将其调整为您的2D阵列。由于您没有提供MCVE,因此它完全未经测试。
Dim rnd As New Random()
For n = total_quizquestions - 1 To 0 Step -1
Dim j = rnd.Next(0, n + 1)
' Swap all three components of the question
For component = 0 To 2
Dim temp = Questions(component, n)
Questions(component, n) = Questions(component, j)
Questions(component, j) = temp
Next component
Next n
而且,只是出于娱乐目的(和后代),这是一个通用的(经过测试的)版本,其中没有“魔术数字”,可以对任何 2D数组进行改组:
Private rnd As New Random()
Sub Shuffle2DArray(Of T)(arr As T(,))
For row = arr.GetUpperBound(1) To arr.GetLowerBound(1) Step -1
Dim swapRow = rnd.Next(0, row + 1)
' Swap all columns of the row
For column = arr.GetLowerBound(0) To arr.GetUpperBound(0)
Dim temp = arr(column, row)
arr(column, row) = arr(column, swapRow)
arr(column, swapRow) = temp
Next column
Next row
End Sub
很明显,您可以将Get...Bound(0)
和Get...Bound(1)
交换为沿2D数组的另一个轴随机播放。