Android Question Short code for generating word list combination?

tufanv

Expert
Licensed User
Longtime User
Hello,

I want to create a short code for generating 3 letter words for all combinations and add them to list. It should be quite easy but couldnt figure out how to do it. If there are 26 letters in the alphabet, we should be creating 26x26x26 different combinations. Any ideas ?

Thanks
 

stevel05

Expert
Licensed User
Longtime User
Maybe something like this:

B4X:
    Dim NumMap As B4XOrderedMap
    NumMap.Initialize
  
  
    Dim I,J,K As Int
    Dim SB As StringBuilder
    For I = 97 To 122
        For J = 97 To 122
            For K = 97 To 122
                SB.Initialize
                SB.Append(Chr(I))
                SB.Append(Chr(J))
                SB.Append(Chr(K))
                NumMap.Put(SB.ToString,1)
            Next
        Next
    Next
  
    Log(NumMap.Keys.Size)
    Log(26*26*26)

A normal Map is about 25% quicker (14ms vs 19 ms on my machine), but this is cross platform, and you can sort the result if needed.
 
Last edited:
Upvote 0

stevel05

Expert
Licensed User
Longtime User
Even quicker if you just use a list. I used a map as i initially though there may be duplicates, but ended up not being any.

B4X:
    Dim StartTime As Long = DateTime.Now
    Dim L As List
    L.Initialize
   
    Dim I,J,K As Int


    For i = 97 To 122
        For J = 97 To 122
            For K = 97 To 122
                L.Add(Chr(I) & Chr(J) & Chr(K))
            Next
        Next
    Next
   
    Log("Complete in " & (DateTime.Now - StartTime) & " ms")
    Log(L.Size)
    Log(26*26*26)
 
Upvote 0

tufanv

Expert
Licensed User
Longtime User
tried this, workinmg perfect ! thanks. Will try the Lucas' eample tomorrow !
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
I was surprised that using StringBuilder doesn't appear to be any quicker than string concatenation, I guess the java compiler optimizes it either way.
 
Last edited:
Upvote 0

Star-Dust

Expert
Licensed User
Longtime User
Congratulations Steve.

A recursive method could also be used. So you can choose how long the word should be without lengthening the code
B4X:
Sub Combine
    Dim StartTime As Long = DateTime.Now
    Dim L As List
    L.Initialize

    Combine(L,"",3)
    Log("Complete in " & (DateTime.Now - StartTime) & " ms")
    Log(L.Size)
    Log(26*26*26)
End Sub

Private Sub Combine(ListComb As List, Prefix As String, Level As Int)
    If Level>0 Then
        For i = 97 To 122
            Combine(ListComb,Prefix & Chr(i), Level-1)
        Next
    Else
        ListComb.Add(Prefix)
    End If
End Sub
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…