Microsoft Office Tutorials and References
In Depth Information
Increment the second value to 4 to get the two-piece fragment 1,4. The third
value in sequence is 5, so you get 1,4,5, at which point your subset size of
3 elements is attained. In your quest for other combinations by varying the
third value, you fi nd none because 5 is already used. Thus with 1,4 you get
1,4,5 only.
Increment the second value to 5 to get 1,5. You fi nd that you have no next
value for the third element.
Increment the fi rst value to 2, set the second element to 3, and get the
combinations 2,3,4 and 2,3,5 and so on to get the remaining combinations
2,4,5 and 3,4,5.
Let’s now examine the function Comb2 . Notice the ByVals in the function
arguments, which cause arguments to be passed by value. When fi rst called
from the subroutine ( Comb2 n, m, 1, "" ), for our example of 5 items taken
3 at a time, the arguments are n=5, m=3, k=1 , and a null string indicating
that the 3-element string is yet to be built.
At the initial entry point, the two Ifs (which we look at more closely later) are
skipped. The line executed is:
Comb2 n, m - 1, k + 1, s & k & " "
Notice that this is a call to the function itself (which is why it is called a recursive
function), with m reduced by 1 (m=2 now) , k incremented by 1 ( k=2 now ),
and the string being set to “ 1 “. The code again skips the two Ifs, and the line
Comb2 n, m - 1, k + 1, s & k & " " calls the function recursively again, with
m=1 , k=3 , and s="1 2 " and then with m=0 , k=4 , and s="1 2 3 “. At this
point, you have obtained the fi rst combination.
When the same line calls the function next, the condition m=0 is satisfi ed, and
the code enters this block:
If m = 0 Then
ActiveCell = s
NumComb = NumComb + 1
ActiveCell.Offset(1, 0).Select
Exit Function
End If
This part of the code enters the combination (‘1 2 3 ‘) in the active cell, activates
the next cell, and exits the last call to the function. Remember that the function
was last called by:
Comb2 n, m - 1, k + 1, s & k & " "
The Exit function makes it branch to the next line, Comb2 n, m, k + 1, s.
At this point, the last value in the string (“1 2 3”) is incremented to the extent
Search JabSto ::

Custom Search