Permutations - Partial List?

Juggler_IN

Active Member
Joined
Nov 19, 2014
Messages
349
Office Version
  1. 2003 or older
Platform
  1. Windows
I want to output the first n of the total permutations. The code below outputs the complete list of the permutations of a given string. For example, for x=1234 there are 24 possible permutations. How can I limit the output to first, say 10, permutations instead of all 24?

VBA Code:
Sub Text()

    Dim x As String, k As Long

    Application.ScreenUpdating = False
    x = "1234"
    ActiveSheet.Columns(1).Clear
    k = 1
    Call PERM("", x, k)
    Application.ScreenUpdating = True

End Sub
Sub PERM(a As String, b As String, ByRef k As Long)

    Dim i As Integer, n As Integer, x

    n = Len(b)
    If n < 2 Then
        Range("A" & k) = "'" & a & b
        k = k + 1
    Else
        For i = 1 To n
            Call PERM(a + Mid(b, i, 1), Left(b, i - 1) + Right(b, n - i), k)
        Next
    End If

End Sub
 

Excel Facts

Excel motto
Not everything I do at work revolves around Excel. Only the fun parts.
Hi,​
just obviously add before the codeline n = Len(b) this codeline : If k = 11 Then Exit Sub …​
 
Upvote 0

Forum statistics

Threads
1,215,004
Messages
6,122,656
Members
449,091
Latest member
peppernaut

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top