随机数字列表 [英] Randomizing a list of numbers
问题描述
我需要对数字(歌曲索引)列表进行随机化处理,以便每个数字都随机排列为随机顺序,并且仅出现一次.它是歌曲播放列表的随机播放功能的一部分,该列表当前可播放13,700首歌曲.这是我到目前为止的内容:
I need to randomize a list of numbers (song indexes) so that each number is shuffled into a random order and appears only once. It''s part of the shuffle function of a song playlist that''s currently 13,700 songs. Here''s what I have so far:
Dim i As Integer
Dim j As Integer
Dim t As Integer
Dim x As Integer
Dim f As Boolean
Dim s As Date
Dim e As Long
Randomize Timer
t = UBound(URLPathList)
s = Now
Do
ReDim Preserve PlayList(i)
f = False
Do
x = Int(Rnd * t + 1)
For j = 0 To i
If PlayList(j) = x Then f = True
Next j
DoEvents
Loop Until f = False
PlayList(i) = x
i = i + 1
Loop Until i = t
e = DateDiff("s", s, Now)
MsgBox e & " seconds"
不幸的是,由于URLPathList的大小约为13,700首歌曲,因此循环和反循环的处理时间太长.这可能是我做这件事的最糟糕的方式.但这是我脑海中的第一个主意.
我需要一种快速,有效的方法来随机分配一个介于0和t之间的数字,以便每个数字至少显示一次且仅显示一次.我将继续尝试一些事情,但是如果有人想出了一个替代方案,使e的计数尽可能小,您将获得一个免费的虚拟cookie.
在此先谢谢您.
Unfortunately, the loops and counterloops take way too long to process as the size of the URLPathList is about 13,700 songs. It''s probably the worst possible way I could have done this. But it was the first idea in my head.
What I need is a fast, efficient way to randomize a list of numbers between 0 and t, so that each number shows up at least once and only once. I''m gonna keep trying a few things, but if someone comes up with an alternate idea that gets the count of e as small as possible, you win a free virtual cookie.
Thanks in advance.
推荐答案
您需要的是随机播放".试试看(用伪代码编写)
What you need is a "shuffle". Try this (written in pseudocode)
initialise an array with the numbers, so arr[i] = i for i = 0 to (13700 or whatever)
repeat until bored (100,000 is probably more than enough)
let q be a random number between 0 and (13700 or whatever)
swap arr[0] and arr[q]
现在您有了所需的数组.这是一种非常简单但有效的技术,它不会永远运行.
彼得
Now you have the array you want. This is a very simple but effective technique, and it won''t take forever to run.
Peter
Dim i As Integer
Dim t As Integer
Dim X As Integer
Dim s As Date
Dim e As Integer
Randomize Timer
t = UBound(URLPathList)
s = Now
For i = 0 To t
ReDim Preserve PlayList(i)
PlayList(i) = -1
Next i
For i = 0 To t
Do
X = Int(Rnd * (t + 1))
Loop Until PlayList(X) = -1
PlayList(X) = i
Next i
e = DateDiff("s", s, Now)
'MsgBox e & " seconds"
仍有更好的方法可以做到这一点.我愿意接受其他方法(如果有).让我知道.
There still may be a better way to do this. I''m open to other methods if you have any. Let me know.
这篇关于随机数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!