ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Recursive Code: How does it work? (https://www.excelbanter.com/excel-programming/369743-recursive-code-how-does-work.html)

Myles[_67_]

Recursive Code: How does it work?
 

The following code attributed to "big Tom" has piqued my interest but
I've failed to get my head around its mechanics-thus farl. Recursive
codes or functions call themseleves in a spiralling loop until a
defator condition is met. I understand all that and have myself set up
a few functions and codes that deploy the recursive character. But
Tom's code is one of a kind, simple and yet powerful and to draw it
mildlymore than a little mystifying. The Code is as follows (shorn of
the ByVal Refs. for simplcity):

Sub Combinations()
Dim n As Integer, m As Integer
numcomb = 0
n = InputBox("Number of items?", , 10)
m = InputBox("Taken how many at a time?", , 3)
com n, m, 1, "'"
End Sub

'Generate combinations of integers k..n taken m at a time, recursively
Sub com(n, m, k, s)
If m n - k + 1 Then Exit Sub
If m = 0 Then
ActiveCell = s
ActiveCell.Offset(1, 0).Select
Exit Sub
End If
com n, m - 1, k + 1, s & k & " "
com n, m, k + 1, s
End Sub


I should be grateful if someone that take me through why n=10, m=3
will
generate the correct 3-sized combinations from the activecell
downwards.


--
Myles
------------------------------------------------------------------------
Myles's Profile: http://www.excelforum.com/member.php...o&userid=28746
View this thread: http://www.excelforum.com/showthread...hreadid=569428



All times are GMT +1. The time now is 10:41 AM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com