Advertisement
Guest User

Untitled

a guest
Apr 1st, 2015
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. /**
  2. * @author beaubordson
  3. */
  4. package hw2;
  5.  
  6. import util.PermutationGenerator;
  7.  
  8. /**
  9. * Utility class for rearranging the characters in a string using a
  10. * <code>PermutationGenerator</code>. The two <code>scramble</code> methods are
  11. * required to use the given <code>PermutationGenerator</code> exactly as
  12. * described.
  13. * <p>
  14. * The methods are static. This class should not be instantiated.
  15. */
  16. public class WordScrambler {
  17. // private constructor prevents accidentally constructing instances
  18. private WordScrambler() {
  19. }
  20.  
  21. /**
  22. * Permutes the characters of the given word according to the next n-element
  23. * permutation produced by the given permutation generator, where n is the
  24. * length of the word.
  25. * <p>
  26. * For example, if the word is "CDEFG" and the next 5-element permutation is
  27. * [2, 0, 4, 1, 3], then the method returns the string "ECGDF".
  28. *
  29. * @param word
  30. * word to be scrambled
  31. * @return scrambled word arranged according to the next appropriately sized
  32. * permutation
  33. */
  34. public static String scramble(String word, PermutationGenerator gen) {
  35. return scramble(word, 0, gen);
  36. }
  37.  
  38. /**
  39. * Permutes the characters of the given word according to the next n-element
  40. * permutation produced by the given permutation generator, where n is the
  41. * length of the word minus <code>fixedCount</code>. Characters with indices
  42. * less than <code>fixedCount</code> are not moved.
  43. * <p>
  44. * For example, if the word is "ABCDEFG" and <code>fixedCount</code> is 2
  45. * and the generator returns the five-element permutation [2, 0, 4, 1, 3],
  46. * then the method returns the string "ABECGDF".
  47. *
  48. * @param word
  49. * word to be scrambled
  50. * @return scrambled word with the first <code>fixedCount</code> letters
  51. * unchanged and remaining letters arranged according to the next
  52. * appropriately sized permutation
  53. */
  54. public static String scramble(String word, int fixedCount,
  55. PermutationGenerator gen) {
  56. String myWord = "";
  57. char[] wordChar = word.toCharArray();
  58. int i;
  59. for (i = 0; i < fixedCount; i++) {
  60. myWord += wordChar[i];
  61. }
  62. int[] generated = gen.generate(word.length() - fixedCount);
  63. for (; i < word.length(); i++) {
  64. myWord += wordChar[generated[i - fixedCount] + fixedCount];
  65. }
  66. return myWord;
  67. }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement