两个各包含100个元素的数组A和B,A按顺序依次存放1-100这100个数,如何打乱顺序,将A的这100个数存放到B中
两个各包含100个元素的数组A和B,A按顺序依次存放1-100这100个数,如何打乱顺序,将A的这100个数存放到B中,使B中存放的这100个数显得毫无规律。
[最优解释]
Option Explicit
Sub Main()
Dim A(1 To 100) As Long
Dim B(1 To 100) As Long
Dim lTmp As Long
Dim i As Long
Dim j As Long
For i = 1 To 100
A(i) = i
Next
'复制 A 到 B
For i = 1 To 100
B(i) = A(i)
Next
'洗牌:将 B(i) 与随机的 B(j) 交换
Randomize
For i = 1 To 100
j = Int(Rnd() * 100) + 1
lTmp = B(i)
B(i) = B(j)
B(j) = lTmp
Next
'查看结果
For i = 1 To 100
Debug.Print i, B(i)
Next
End Sub
1L用了List,我用了集合.
Dim col As New Collection
Dim i As Long, b(1 To 100) As Long
Dim r As Long
For i = 1 To 100
col.Add i, CStr(i)
Next i
Randomize
For i = 1 To 100
r = (Rnd * 100 + 1) Mod col.Count + 1
b(i) = col.Item(r)
col.Remove (r)
Next i
For i = 1 To 100
Debug.Print b(i);
Next i