Mixed Up Letters - String Functions

  Processing Code      Standard Java Code

/*******************************************
Woody Wordword likes to play Scrabble.  He wants to practice
on his own, when no other players are available.  His idea is
to have the computer choose a random word, then scramble up
the letters and display the result.  Then he tries to guess
the original word, types his guess, and the computer tells
him whether he was correct. 
********************************************/

String[] words = {"hopeful", "unhappy", "worried", "liberty",
                  "general", "trigger", "napkins", "showing",
                  "legible", "rotated", "parsing", "fiddler"
                 };
void setup()
{
   String chosen = chooseWord();
   output("The mixed up letters are: \n" + mixup(chosen));
   String answer = input("Your answer");
   if(answer.equalsIgnoreCase(chosen))
   {  output("Well done"); }
   else
   {  output("No, the word was " + chosen); } 
}

String chooseWord()
{
   int num = (int)(Math.random()*words.length);
   return words[num];
}

String mixup(String w)
{
   // take individual letters and store in an array
   // swapping is much easier in an array than a String
   String[] letters = new String[w.length()];
   for(int x = 0; x < w.length(); x=x+1)
   {
      letters[x] = w.substring(x,x+1);
   }
  
   // choose two random letters and swap, repeat 10 times
   for(int x = 0; x < 10; x=x+1)
   {
      int a = (int)(Math.random()*w.length());
      int b = (int)(Math.random()*w.length());
      String temp = letters[a];
      letters[a] = letters[b];
      letters[b] = temp;
   } 
   
   // concatenate letters from array back into a String
   String result = ""; 
   for(int x = 0; x < w.length(); x = x+1)
   {
      result = result + letters[x];      
   }
   
   return result;
}

public String input(String prompt)
{ return javax.swing.JOptionPane.showInputDialog(null,prompt); }
 
public void output(String message)
{  javax.swing.JOptionPane.showMessageDialog(null,message);  }

Random Numbers

The program scrambles the letters of a word as follows:

The RANDOM positions are chosen by the Math.random( ) function.  It works like this:

Scrambling Letters

The scrambling algorithm works like this:

Programming Practice