2008年6月17日 星期二

不重複的亂數(ASP)

'ProduceRan(開始範圍, 結束範圍, 取多少個),註結束範圍-開始範圍需大於所取數目
call ProduceRan(1,101,100)

'產生n~m不重複亂數列
Sub ProduceRan(staNum,endNum,Validx)
if (endNum - staNum) < Validx then
 response.write "欲取數目大於設定範圍,無法計算!!"
 exit sub
end if

x = Validx
Dim theRanArray()
ReDim theRanArray(x)

'設定陣列初始值
for ValIdx = 0 to UBound(theRanArray)
 theRanArray(ValIdx) = 0
next

'與已知亂數比對,若重複則再取一次
for theRanIdx = 0 to UBound(theRanArray)
 theRan = ranValue(staNum,endNum)

 doubled = 0
 for checkIdx = 0 to UBound(theRanArray)
  if theRan = theRanArray(checkIdx) then doubled = 1 end if
 next

 if doubled = 0 then
  theRanArray(theRanIdx) = theRan 
 else
  theRanIdx = theRanIdx - 1 
 end if
next

'印出最後產生完成的亂數陣列
for prtIdx = 0 to UBound(theRanArray)
response.write theRanArray(prtIdx) & "
"
next

End Sub


'取得亂數函數
Function ranValue(beginNum,endNum)
 ' Initialize the random-number generator.
 Randomize()
 ' Generate random value between 1 and 6.
 ranValue = CInt(Int((endNum * Rnd()) + beginNum))
End Function


沒有留言: