shuffle string of array

MLDev

Active Member
Licensed User
Longtime User
B4X:
' Knuth's Algorithm P
Dim n As Int = alphabets.Length
Dim r As Int
Dim t As String
   
For i = 0 To n - 1
   r = Rnd(i, n)
   t = alphabets(i)
   alphabets(i) = alphabets(r)
   alphabets(r) = t
Next
 
Upvote 0

sanjibnanda

Active Member
Licensed User
Longtime User
shuffle Array As string

B4X:
' Knuth's Algorithm P
Dim n As Int = alphabets.Length
Dim r As Int
Dim t As String
   
For i = 0 To n - 1
   r = Rnd(i, n)
   t = alphabets(i)
   alphabets(i) = alphabets(r)
   alphabets(r) = t
Next

Thanks for hint MLdev ... i converted it to sub , may be helpful for some Newbie

B4X:
Sub ShuffleArray(arr() As String)
   Dim n As Int = arr.Length-1
Dim r As Int
Dim t As String
    
For i = 0 To n - 1
    r = Rnd(i, n)
    t = arr(i)
    arr(i) = arr(r)
    arr(r) = t
Next
Return arr
End Sub

How to use
B4X:
ShuffleArray(YourArr)
B4A forum is wonderful as long as people like you live there...

it worked like a charm...thanks again to you and Knuth's Algorithm P
regards
sanjib
 
Upvote 0

MLDev

Active Member
Licensed User
Longtime User
With this line in your sub:

B4X:
Dim n As Int = arr.Length-1

The last element in the array will always be the same. It should be:

B4X:
Dim n As Int = arr.Length

EDIT

And this line in my code:

B4X:
For i = 0 To n - 1

should be:

B4X:
For i = 0 To n - 2

:signOops:
 
Last edited:
Upvote 0

DrownedBat

Member
Licensed User
Longtime User
Any way to reverse this process?

take alphabets = {"C", "A", "I", "D", "G", "J", "H", "H", "B", "F"};
and arrange it back into alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
I guess the easiest would be to loop through the elements and put them into a list, sort the list, write it back to the array.

or you can write your own sort routine on the array.
 
Upvote 0
Top