Seu exemplo indicou 12 itens. Este código (fornecido por John Coleman em 2005) listará as 4095 permutações da lista na coluna B . Existem 2 itens N -1:
Sub MAIN()
B = Array("a", "b", "c", "d", "q", "w", "e", "r", "z", "x", "v", "p")
Call GrayCode(B)
End Sub
Function GrayCode(Items As Variant) As String
Dim CodeVector() As Integer
Dim i, kk As Integer
Dim lower As Integer, upper As Integer
Dim SubList As String
Dim NewSub As String
Dim done As Boolean
Dim OddStep As Boolean
kk = 1
OddStep = True
lower = LBound(Items)
upper = UBound(Items)
ReDim CodeVector(lower To upper) 'it starts all 0
Do Until done
'Add a new subset according to current contents
'of CodeVector
NewSub = ""
For i = lower To upper
If CodeVector(i) = 1 Then
If NewSub = "" Then
NewSub = "," & Items(i)
Else
NewSub = NewSub & "," & Items(i)
End If
End If
Next i
If NewSub = "" Then NewSub = "{}" 'empty set
SubList = SubList & vbCrLf & NewSub
Cells(kk, 2) = Mid(NewSub, 2)
kk = kk + 1
'now update code vector
If OddStep Then
'just flip first bit
CodeVector(lower) = 1 - CodeVector(lower)
Else
'first locate first 1
i = lower
Do While CodeVector(i) <> 1
i = i + 1
Loop
'done if i = upper:
If i = upper Then
done = True
Else
'if not done then flip the *next* bit:
i = i + 1
CodeVector(i) = 1 - CodeVector(i)
End If
End If
OddStep = Not OddStep 'toggles between even and odd steps
Loop
GrayCode = SubList
End Function
Referência:
Você pode alterar / adicionar / remover itens alterando o Array()
. Muitos irão transbordar os limites para o número de itens em uma coluna.