montecarlo2012
Well-known Member
- Joined
- Jan 26, 2011
- Messages
- 986
- Office Version
- 2010
- Platform
- Windows
Generate a VBA code that generate 20 rows of length 5 from a set of 12 numbers, that meet the specific frequency of each number, no permutations.
DISPLAY AT F2:J21
this code generate repetition in the rows or permutations, and the frequency is wrong also,
please somebody can check where is the problem.
thank you for reading this
DISPLAY AT F2:J21
frequency for | 1 | equal | 8 |
frequency for | 2 | equal | 7 |
frequency for | 3 | equal | 9 |
frequency for | 4 | equal | 10 |
frequency for | 5 | equal | 11 |
frequency for | 6 | equal | 10 |
frequency for | 7 | equal | 11 |
frequency for | 8 | equal | 7 |
frequency for | 9 | equal | 6 |
frequency for | 10 | equal | 5 |
frequency for | 11 | equal | 7 |
frequency for | 12 | equal | 9 |
VBA Code:
Sub GenerateCombinations()
Dim numbers(1 To 12) As Integer
Dim frequencies(1 To 12) As Integer
Dim combinations(1 To 20, 1 To 5) As Integer
Dim i As Integer, j As Integer, k As Integer, n As Integer, count As Integer
Dim temp As Integer
' Set the numbers and their frequencies
numbers(1) = 1
numbers(2) = 2
numbers(3) = 3
numbers(4) = 4
numbers(5) = 5
numbers(6) = 6
numbers(7) = 7
numbers(8) = 8
numbers(9) = 9
numbers(10) = 10
numbers(11) = 11
numbers(12) = 12
frequencies(1) = 8
frequencies(2) = 7
frequencies(3) = 9
frequencies(4) = 10
frequencies(5) = 11
frequencies(6) = 10
frequencies(7) = 11
frequencies(8) = 7
frequencies(9) = 6
frequencies(10) = 5
frequencies(11) = 7
frequencies(12) = 9
' Generate combinations
For i = 1 To 20
' Reset count for each combination
count = 0
' Generate a combination of 5 unique numbers
Do While count < 5
n = Int((12 * Rnd) + 1) ' Generate a random number between 1 and 12
If frequencies(n) > 0 Then ' Check if frequency of the number is not exceeded
combinations(i, count + 1) = numbers(n) ' Add the number to the combination
frequencies(n) = frequencies(n) - 1 ' Decrease the frequency of the number
count = count + 1 ' Increase the count of numbers in the combination
End If
Loop
' Reset frequencies for the next combination
For j = 1 To 12
frequencies(j) = frequencies(j) + 1
Next j
Next i
' Sort the combinations
For i = 1 To 19
For j = i + 1 To 20
For k = 1 To 4
If combinations(i, k) > combinations(j, k) Then
For n = 1 To 5
temp = combinations(i, n)
combinations(i, n) = combinations(j, n)
combinations(j, n) = temp
Next n
ElseIf combinations(i, k) = combinations(j, k) And combinations(i, k + 1) > combinations(j, k + 1) Then
For n = 1 To 5
temp = combinations(i, n)
combinations(i, n) = combinations(j, n)
combinations(j, n) = temp
Next n
End If
Next k
Next j
Next i
' Display the combinations
Range("F2:J21") = combinations
End Sub
please somebody can check where is the problem.
thank you for reading this