Scramble Word with Java

I wanted to scramble String to make it unreadable and therefore came up with this method:

public String scrambleWord(String start_word){

     char[] wordarray = start_word.toCharArray();

        char[] dummywordarray = start_word.toCharArray();

        Random random = new Random();

        int r = random.nextInt(wordarray.length-1);
        int i = 0;

        int j = r+1;

        while(i <= r){

            dummywordarray[wordarray.length -i-1] = wordarray[i];

            i++;
        }


        while (j <= wordarray.length -1){

            dummywordarray[j-r-1] = wordarray[j];

            j++;

        }

        String newword = String.valueOf(dummywa);



        return newword;

SO I first converted the string to a char array, and in my method I had to duplicate the char array "dummywordarray". After going through this algorithm once, each word will be changed. But he will not climb very well, in the sense that you could bring him back at a glance. SO I transmitted a given string of less than 9 characters by the method 7 times, and the words are pretty well scrambled, i.e. unreadable. But I tried it with a 30-character string, and it took 500 pass before I could guarantee that it was well-scrambled. 500! I am sure that there is a better algorithm, I would like a) to improve this method or b) a better way.

+5
1

ArrayList<Character> chars = new ArrayList<Character>(word.length());
for ( char c : word.toCharArray() ) {
   chars.add(c);
}
Collections.shuffle(chars);
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
   shuffled[i] = chars.get(i);
}
String shuffledWord = new String(shuffled);

, java.util.Collections.shuffle(List). , , , Generics.

:

shuffle (. Javadoc ):

for position = last_index to first_index
   let swap_pos = random number between first_index and position, inclusive
   swap(swap_pos, position)

2:

Guava Chars:

List<Character> chars = Chars.asList(word.toCharArray());
Collections.shuffle(chars);
String shuffledWord = new String(Chars.toArray(chars));
+18

All Articles