#Shuffling a Word

13 messages · Page 1 of 1 (latest)

tulip ravine
#

Hi I am trying to shuffle a word completely randomly and this is what I have done (using the fischer-yates method)

private static String scrambleWord(String randomWord) {
        /** Scrambles the random word chosen from the text file 
         * 
         * @param randomWord A string with the word randomly chosen from the list of words 
         * @return scrambledWord A string with the word chosen shuffled at random 
         */

        // Convert string to an array of characters 
        char[] wordArray = randomWord.toCharArray(); 

        Random random = new Random(); 

        // Start from last element and swap each time 
        for (int i = wordArray.length-1; i >= 0; i--) {

            // Pick a random index 
            int j = random.nextInt(i+1); 

            // Swap specific index with random index
            char letter = wordArray[i];
            wordArray[i] = wordArray[j];
            wordArray[j] = letter;  
        }

        String scrambledWord = String.valueOf(wordArray);  

        return scrambledWord; 

    }

However, sometimes I find that on the off chance this happens:

lucid garnetBOT
#

This post has been reserved for your question.

Hey @tulip ravine! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

tulip ravine
#

This seems to only be happening with three letter words like EGG and KEY

timid granite
#

There’s a 1/6 chance of that happening for 3 letter words

#

1/24 for four letters

#

Assuming a fully random scramble anyways

tulip ravine
#

It seems not to give me any original words now

timid granite
#

It was probably just scrambling to the original word, the only scrambles of pen are
PEN
ENP
NPE
NEP
EPN
PNE

tulip ravine
#

Yeah I figured as much thank you!

lucid garnetBOT
# tulip ravine Yeah I figured as much thank you!

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.