B4J Code Snippet Randomize Re-Sort List

Hi there...

Yesterday update the google drive link for B4XDesigner and needed to add the "Names" of programmers "loose" their time (i think that all win - when sharing knowledge and ideas) for this project... but I want to be fair by showing all names contribute in that big project...

1711783501308.png



so needed to randomize the sort of the list... thought this way... i am sure there are better ways (you can share them here)

Well my way:


B4X:
Sub shownames
    Dim allnames As List
    allnames.Initialize
    allnames.Add("Georgios Kantzas - MAGMA")
    allnames.Add("Aeric")
    allnames.Add("OliverA")
    allnames.Add("zed")
    allnames.Add("CableGuy")
    allnames.Add("Walterf25")
    allnames.Add("Jahwsant")
    allnames.Add("Jakebullet70")
    allnames.Add("Alexander Stolte")
    lblAbout.Text = "B4XDesigner About..." & CRLF & CRLF & "Created by (Randomized Series):" & CRLF & CRLF & showrndlist(allnames) & CRLF & CRLF & "Click Names to re-sort..."
End Sub

Sub showrndlist(aa As List) As String
    Dim how As Int = aa.Size
    Dim newlist As List
    Dim newtext As String
    newlist.Initialize
    For k=0 To how-1
        newlist.Add(aa.Get(k))   
    Next

    Dim a As Int
    Dim b As Int
    Dim c As String
    Dim d As String

    For k=0 To NumberFormat2((how-1)/2,0,0,0,False)

        Do Until a<>b
        a =Rnd(0,how)
        b =Rnd(0,how)
        Loop
       
        c=newlist.Get(a)
        d=newlist.Get(b)
       
        newlist.Set(a,d)
        newlist.Set(b,c)

    Next
   
    For k=0 To how-1
        newtext=newtext & newlist.Get(k)
        If k<how-1 Then
            newtext=newtext & ", "
        End If
    Next
   
    Return newtext
End Sub



Private Sub lblAbout_MouseClicked (EventData As MouseEvent)
    shownames
End Sub
 

Daestrum

Expert
Licensed User
Longtime User
B4X:
Sub Process_Globals
    Dim collections As JavaObject
    Dim random As JavaObject
End Sub

Sub AppStart (Args() As String)

    collections.InitializeStatic("java.util.Collections")
    random.InitializeNewInstance("java.util.Random",Array(DateTime.Now))

    Dim myList As List
    myList.Initialize
    myList.AddAll(Array As String("Element 1", "Element 2", "Element 3", "Element 4", "Element 5")) ' Add your elements here

    collections.RunMethod("shuffle",Array(myList,random))

    For Each element In myList
        Log(element)
    Next
End Sub
 

PaulMeuris

Active Member
Licensed User
Not using Java...
B4X:
Private Sub showrndlist(names As List) As String
    Dim strnames As String
    Dim nmap As Map
    nmap.Initialize
    For i = 0 To names.Size -1
        nmap.put(i,names.Get(i))
    Next
    Do Until nmap.Size = 0
        Dim pos As Int = Rnd(0,names.Size)
        If nmap.Size > 0 And nmap.ContainsKey(pos) Then
            strnames = strnames & names.Get(pos) & CRLF
            nmap.Remove(pos)
        End If
    Loop
    Return strnames
End Sub
 
Top