# shuffle string of array

#### sanjibnanda

##### Active Member
Longtime User
HTML:
``````Hi ,

How can i shuffle string of array

alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};

TO SOME RANDOM STATE LIKE

alphabets = {"C", "A", "I", "D", "G", "J", "H", "H", "B", "F"};``````

#### MLDev

##### Active Member
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``````

#### sanjibnanda

##### Active Member
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

#### MLDev

##### Active Member
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:

Longtime User

#### DrownedBat

##### Member
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"};

#### sorex

##### Expert
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.

#### Erel

##### B4X founder
Staff member
Longtime User
Use a list instead of an array and call List.Sort to sort the items.

Replies
7
Views
2K
Replies
17
Views
3K
Android Code Snippet Randomly shuffle a string array
Replies
13
Views
8K
Android Code Snippet ShuffleList
Replies
5
Views
5K
Replies
5
Views
7K