Advertisement
NYCJacob

letter swap

Sep 13th, 2014
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.23 KB | None | 0 0
  1.  
  2. //Translate the following pseudocode for randomly permuting the characters in
  3. //a string into a method in the given Java class.
  4.  
  5. //Read a word.
  6. //Repeat word.length() times
  7. //   Pick a random position i in the word, but not the last position.
  8. //   Pick a random position j > i in the word. (this is tricky)
  9. //   Swap the letters at positions j and i.
  10. //Print the word.
  11.  
  12. //To swap the letters, construct substrings as follows:
  13.  
  14. //   http://i.imgur.com/re4bGPu.png
  15.  
  16. //Create and return the string:
  17. //   first + word.substring(j, j + 1) + middle
  18. //         + word.substring(i, i + 1) + last
  19.  
  20. // Need help starting this question? In the lesson titled
  21. // "Starting points: Problem Set Questions", go to the
  22. // problem titled "Problem Set 5 - Question 2" for some tips on
  23. // how to begin.
  24.  
  25. //I recommend that you implement and test the swapping before implementing
  26. //the loop. If something is wrong in the swap, it will be much more difficult
  27. //to find it you have executed the swap many times. That is an example of
  28. //step-wise refinement. Code a little, test, code a little more.
  29.  
  30. import java.util.Random;
  31. /**
  32.  
  33.  */
  34. public class Word
  35. {
  36.    private Random generator = new Random();
  37.  
  38.    public Word()  //leave the constructor alone
  39.    {
  40.         generator = new Random();
  41.         final long SEED = 42;
  42.         generator.setSeed(SEED);
  43.    }
  44.    /**
  45.     * Gets a version of this word with the leters scrambled
  46.     * @param word the string to scramble
  47.     * @return the scrabled string
  48.     */
  49.    public String scramble(String word)
  50.    {
  51.         //TODO scramble the letters following the pseudocode
  52.        int wordLen = word.length();
  53.        int i;
  54.        int j;
  55.        String result = word;
  56.        String first = "";
  57.        String middle = "";
  58.        String last = "";
  59.        
  60.        for (int count = 0; count < wordLen; count++)
  61.        {
  62.            i = generator.nextInt(wordLen - 1);
  63.            j = generator.nextInt(wordLen - i -1) + i + 1;
  64.            first = result.substring(0, i);
  65.            middle = result.substring(i +1, j);
  66.            last = result.substring(j + 1);
  67.            result = first + word.substring(j, j + 1) + middle + word.substring(i, i + 1) + last;
  68.        }
  69.  
  70.        return result;
  71.    }
  72.  
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement