Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. package edu.wit.cs.comp1050;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class Shifter {
  6.  
  7. /**
  8. * Number of letters in the English alphabet
  9. */
  10. public static final int NUM_LETTERS = ('z' - 'a') + 1;
  11.  
  12. private String s;
  13.  
  14. /**
  15. * Initializes the shifter
  16. *
  17. * @param s encrypted string
  18. */
  19. public Shifter(String s) {
  20. this.s = s;
  21. }
  22.  
  23. /**
  24. * Returns the result of shifting by a supplied amount
  25. *
  26. * @param n number of places to shift
  27. * @return shifted string
  28. */
  29. public String shift(int n) {
  30.  
  31. StringBuilder newString = new StringBuilder();
  32.  
  33. char[] letters = s.toCharArray();
  34.  
  35. if (s.isEmpty()) {
  36. return "";
  37. }
  38.  
  39. else if (s == " ") {
  40. return " ";
  41. }
  42.  
  43. if (n > 26 || n < -26) {
  44. n = n % 26;
  45. }
  46.  
  47. for (int i = 0; i < letters.length; i++) {
  48. if (letters[i] >= 'a' && letters[i] <= 'z') {
  49.  
  50. if (letters[i] + n < 'a') {
  51. letters[i] = (char) ((letters[i] + n) + 26);
  52. } else if (letters[i] + n > 'z') {
  53. letters[i] = (char) ((letters[i] + n) - 26);
  54. }
  55.  
  56. else {
  57. letters[i] = (char) (letters[i] + n);
  58. }
  59.  
  60. }
  61.  
  62. if (letters[i] >= 'A' && letters[i] <= 'Z') {
  63. if (letters[i] + n < 'A') {
  64. letters[i] = (char) ((letters[i] + n) + 26);
  65. } else if (letters[i] + n > 'Z') {
  66. letters[i] = (char) ((letters[i] + n) - 26);
  67. } else {
  68. letters[i] = ((char) (letters[i] + n));
  69. }
  70. }
  71. }
  72. for (int i = 0; i < letters.length; i++) {
  73. newString.append(letters[i]);
  74. }
  75. return newString.toString();
  76. }
  77.  
  78. /**
  79. * Finds all shifts that contain the supplied substring
  80. *
  81. * @param sub substring to find
  82. * @return array of shifts (0-25) that contain the substring (in order)
  83. */
  84. public int[] findShift(String sub) {
  85.  
  86. String method;
  87. ArrayList<Integer> shifts = new ArrayList<>();
  88.  
  89. int count = 0;
  90. for (int i = 0; i <= 25; i++) {
  91.  
  92. method = shift(count);
  93.  
  94. if (method.contains(sub)) {
  95.  
  96. shifts.add(i);
  97.  
  98. }
  99. count++;
  100. }
  101.  
  102. int[] numShifts = new int[shifts.size()];
  103.  
  104. for (int i = 0; i < numShifts.length; i++) {
  105.  
  106. numShifts[i] = shifts.get(i);
  107.  
  108. }
  109. return numShifts;
  110. }
  111.  
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement