Sub ChinhHopChap_k()
Dim DuLieu$, aToHop, aHoanVi(), Res()
Dim srTH&, srHV&, N&, k&, i&, r&, id&, j&
Dim sTH$, tmp$, str$
DuLieu = "12579" 'Chuoi cac ky tu so
k = 2 'So ky tu ket qua
N = Len(DuLieu)
str = String(k, "#")
aHoanVi = HoanVi(k)
Call ChuyenMangSo(aHoanVi, k)
aToHop = Tohop_N_Chap_K(N, k)
srTH = UBound(aToHop): srHV = UBound(aHoanVi)
ReDim Res(1 To srTH * srHV)
For i = 1 To srTH
sTH = aToHop(i, 1)
tmp = Empty
For j = 1 To N
If Mid(sTH, j, 1) = "1" Then
tmp = tmp & Mid(DuLieu, j, 1)
End If
Next j
For r = 1 To srHV
For j = 1 To k
Mid(str, j, 1) = Mid(tmp, aHoanVi(r, j), 1)
Next j
id = id + 1
Res(id) = str
Next r
Next i
Range("A2").NumberFormat = "@"
Range("A2") = Join(Res, ",")
End Sub
Function Tohop_N_Chap_K(ByVal N As Long, ByVal k As Long) As Variant
'Tao to hop N chap K, bieu dien bang chuoi các ký tu "0" va "1"
'Thu tu gia tri "1" là thu tu du lieu nguon lay du lieu
Dim Arr() As String, tmp$, j&, p&, S&
ReDim Arr(1 To Application.Combin(N, k), 1 To 1)
tmp = String(k, "1") & String(N - k, "0")
p = 1: Arr(p, 1) = tmp
If k = N Then Tohop_N_Chap_K = Arr: Exit Function
Do
j = InStrRev(tmp, "1")
Mid(tmp, j, 1) = "0"
Mid(tmp, j + 1, S + 1) = String(S + 1, "1")
S = 0: p = p + 1: Arr(p, 1) = tmp
If InStr(j + 1, tmp, "0") = 0 Then
S = N - j
Mid(tmp, j + 1, S) = String(S, "0")
End If
Loop Until S = k
Tohop_N_Chap_K = Arr
End Function
Function HoanVi(ByVal Q&)
'Q là so gia tri can hoan vi, gioi han tu 1 toi 9
'Tao Hoan Vi cua Q so, bieu dien bang chuoi cac so thu tu
Dim Res(), Arr, N&, i&, k&, j As Double, sRow&
ReDim Res(1 To 1, 1 To 1)
Res(1, 1) = "1"
For N = 2 To Q
Arr = Res: k = 0
sRow = UBound(Arr)
ReDim Res(1 To N * sRow, 1 To 1)
For j = 1 To sRow
k = k + 1
Res(k, 1) = Arr(j, 1) & N
For i = N To 2 Step -1
k = k + 1
Res(k, 1) = Res(k - 1, 1)
Mid(Res(k, 1), i, 1) = Mid(Res(k, 1), i - 1, 1)
Mid(Res(k, 1), i - 1, 1) = N
Next
Next
Next N
HoanVi = Res
End Function
Sub ChuyenMangSo(ByRef aHoanVi, ByVal k&)
Dim Res(), sRow&, i&, j&, tmp$
sRow = UBound(aHoanVi)
ReDim Res(1 To sRow, 1 To k)
For i = 1 To sRow
tmp = aHoanVi(i, 1)
For j = 1 To k
Res(i, j) = CLng(Mid(tmp, j, 1))
Next j
Next i
aHoanVi = Res
End Sub