B4A Library [B4X][B4XLib] lmB4XPermutations

Small library that generates all possible permutations of a given list of items (of any type).

Library and example attached (there is no B4i example but it is a B4XPages project, just select the library and create the layout - copy it from the B4A project).

B4X:
    Dim lstItems As List
    lstItems.Initialize
    lstItems.AddAll(Array ("A", "B", "C", "D"))
   
    Wait For (lmB4XPermutations.Generate(lstItems)) Complete(lstPermutations As List)
    For Each lst As List In lstPermutations
        Logs.Text = Logs.Text & lst & CRLF 'ignore
    Next
   
    Logs.Text = Logs.Text & CRLF & lstPermutations.Size & " lists."

1736713361283.png
 

Attachments

  • lmB4XPermutations.b4xlib
    1.3 KB · Views: 11
  • lmB4XPermutationsTest.zip
    14 KB · Views: 9
Last edited:

LucaMs

Expert
Licensed User
Longtime User
To add it or not to add it, that is the question.

amleto.jpg


B4X:
' Generate all non-repeating combinations of K elements from a given list.
' The order of elements does not matter.
Public Sub CreateCombinations(lstItems As List, K As Int) As List
    Dim lstCombinations As List
    lstCombinations.Initialize
   
    ' Check that K is valid
    If K <= 0 Or K > lstItems.Size Then
        Log("The value of K is not valid.")
        Return Null
    End If
   
    ' Generate all non-repeating combinations of K elements
    Dim indices(K) As Int
    For i = 0 To K - 1
        indices(i) = i
    Next
   
    Do While True
        Dim combination As List
        combination.Initialize
       
        ' Build the current combination
        For i = 0 To K - 1
            combination.Add(lstItems.Get(indices(i)))
        Next
       
        ' Add the combination to the list of combinations
        lstCombinations.Add(combination)
       
        ' Find the index to increment
        Dim j As Int = K - 1
        Do While j >= 0 And indices(j) = lstItems.Size - K + j
            j = j - 1
        Loop
       
        ' If all indices are exhausted, exit
        If j < 0 Then
            Exit
        End If
       
        ' Increment the found index
        indices(j) = indices(j) + 1
       
        ' Set the next indices
        For i = j + 1 To K - 1
            indices(i) = indices(i - 1) + 1
        Next
    Loop
   
    Return lstCombinations
End Sub

The problem is the name I gave to the library.
Adding CreateCombinations to it would be "logical".

Please, give me a suggestion 😊 Thank you.
 
Top