#### montecarlo2012

##### Active Member

- Joined
- Jan 26, 2011

- Messages
- 364

I have been trying to work around this code, I need some hands on here, Please.

I am trying to generate all possible combinations and permutations possible from the set of numbers from 0 to 9 taken four at a time BUT display ONLY the one’s that match the conditions.

The condition that I tried is to have control on odd and even numbers per row and the sum.

The odd and even in this case is only five possible outcomes :

Code:

```
[TABLE="width: 128"]
<colgroup><col width="64" span="2" style="width:48pt"> </colgroup><tbody>[TR]
[TD="class: xl63, width: 64"]odds [/TD]
[TD="class: xl63, width: 64"]even[/TD]
[/TR]
[TR]
[TD="class: xl64, align: right"]0[/TD]
[TD="class: xl64, align: right"]4[/TD]
[/TR]
[TR]
[TD="class: xl64, align: right"]1[/TD]
[TD="class: xl64, align: right"]3[/TD]
[/TR]
[TR]
[TD="class: xl64, align: right"]2[/TD]
[TD="class: xl64, align: right"]2[/TD]
[/TR]
[TR]
[TD="class: xl64, align: right"]3[/TD]
[TD="class: xl64, align: right"]1[/TD]
[/TR]
[TR]
[TD="class: xl64, align: right"]4[/TD]
[TD="class: xl64, align: right"]0[/TD]
[/TR]
</tbody>[/TABLE]
```

Also I would like to avoid this two lines

Set rRng = Range("A1", Range("A1").End(xlDown))

rRng.Select: p = 4

because I already know the set of number, and is always 4, but I don’t know how to do it.

The display could start at ("D2")

Thank you.

Code:

```
Option Explicit
Public sumArr As Long, oddNo As Long, evenNo As Long, oddNoReq As Long, lastRow As Long, _
evenNoReq As Long, minSumValue As Long, maxSumValue As Long, lRow As Long, testRow As Long, minMaxRn As Long
Sub Combinations()
oddNoReq = Range("B27"): evenNoReq = Range("B26")
minSumValue = Range("B29"): maxSumValue = Range("B30")
Dim rRng As Range, p As Integer
Dim vElements, vresult As Variant
lRow = 1
testRow = 1
Set rRng = Range("A1", Range("A1").End(xlDown))
rRng.Select: p = 4
vElements = Application.Index(Application.Transpose(rRng), 1, 0)
ReDim vresult(1 To p): Columns("C").Resize(, p + 12).Clear
Call CombinationsNP(vElements, p, vresult, lRow, 1, 1)
End Sub
Sub CombinationsNP(vElements As Variant, p As Integer, vresult As Variant, lRow As Long, iElement As Integer, iIndex As Integer)
Dim i As Integer, k As Integer
For i = iElement To UBound(vElements)
vresult(iIndex) = vElements(i)
If iIndex = p Then
For k = LBound(vresult) To UBound(vresult)
If vresult(k) Mod 2 <> 0 Then oddNo = oddNo + 1
If vresult(k) Mod 2 = 0 Then evenNo = evenNo + 1
sumArr = sumArr + vresult(k)
Next k
If oddNo = oddNoReq And evenNo = evenNoReq _
And sumArr >= minSumValue _
And sumArr <= maxSumValue Then
lRow = lRow + 1
Range("S" & lRow) = sumArr
End If
testRow = testRow + 1
Range("k" & testRow).Resize(, p) = vresult
End If
If iIndex <> p Then
Call CombinationsNP(vElements, p, vresult, lRow, i + 1, iIndex + 1)
End If
Next i
End Sub
```