|
Option Explicit
Sub test()
Dim ar, t#
t = Timer
ar = rndNumIsTotalSum(40, 43, 7, [A2].Value)
[B2].Resize(, UBound(ar)) = ar
End Sub
Function rndNumIsTotalSum(ByVal iMinNum&, ByVal iMaxNum&, ByVal iCount&, ByVal iSumNum&)
Dim ar(), i&, iAverage&, iRnd1&, iRnd2&, iRndNum&, iBal1&, iBal2&
ReDim ar(1 To iCount)
iAverage = Int(iSumNum / iCount)
If iAverage < iMinNum Or iAverage > iMaxNum Then
For i = 1 To UBound(ar): ar(i) = "无解!": Next
rndNumIsTotalSum = ar: Exit Function
End If
For i = 1 To UBound(ar)
ar(i) = iAverage
Next i
For i = 1 To (iSumNum - iAverage * iCount)
ar(i) = ar(i) + 1
Next i
Randomize
For i = 1 To iCount
iRnd1 = Int(iCount * Rnd + 1): iRnd2 = Int(iCount * Rnd + 1)
iBal2 = iMaxNum - ar(iRnd2): iBal1 = ar(iRnd1) - iMinNum
If iBal2 < iBal1 Then iRndNum = iBal2 Else iRndNum = iBal1
ar(iRnd1) = ar(iRnd1) - iRndNum
ar(iRnd2) = ar(iRnd2) + iRndNum
Next i
rndNumIsTotalSum = ar
End Function
|
|