Home All Groups Group Topic Archive Search About

writing function for permutation

Author
2 Feb 2006 5:10 AM
dave
Hi There
Can anyone help to write permutation function for following formula..
nPr = n!/(n-r)!
where n is length of given string and r is lengh of subset..
for example..if given string is "abcd" and r = 2 then out put shuld be
ab
ac
ad
ba
bc
bd..and so on...

and if r = 3 then output shuld be
abc
abd
acb
acd and so on...

Any help would be highly appreciated..
thnx
dave

Author
2 Feb 2006 12:34 PM
J French
On Thu, 2 Feb 2006 16:10:12 +1100, "dave" <noj***@nojunk.com> wrote:

>Hi There
>Can anyone help to write permutation function for following formula..
>nPr = n!/(n-r)!
>where n is length of given string and r is lengh of subset..
>for example..if given string is "abcd" and r = 2 then out put shuld be
>ab
>ac
>ad
>ba
>bc
>bd..and so on...

I think this is what you want :-
Option Explicit: DefObj A-Z

' Combinations : J French 7th Aug 03

Private Sub Command1_Click()
    Dim Dest$

    Call LS_Combine(2, "", "ABCDE", Dest$)
    Me.AutoRedraw = True
    Me.Print Dest$
    'Open "c:\t\test.txt" For Output As #1
    'Print #1, Dest$
    'Close #1

End Sub

Private Sub LS_Combine(SampleSize%, RootIn$, FullSetIn$, Dest$)
    Dim L9%, Root$, NewFullSetIn$

    ' --- At bottom - take result and exit
    If SampleSize = 0 Then
       Dest$ = Dest$ + RootIn$ + vbCrLf
       Exit Sub
    End If

    ' --- For each possible Start Letter
    For L9 = 1 To Len(FullSetIn$)
        ' --- Build Root
        Root$ = RootIn$ + Mid$(FullSetIn$, L9, 1)
        NewFullSetIn$ = Left$(FullSetIn$, L9 - 1) _
                        + Mid$(FullSetIn$, L9 + 1)
        ' --- Handle Residue
        Call LS_Combine(SampleSize% - 1, _
                        Root$, _
                        NewFullSetIn$, _
                        Dest$)
    Next

End Sub