Browse Source

epiphany refactor

Jared Norris 6 years ago
parent
commit
b3de406b05
1 changed files with 8 additions and 19 deletions
  1. 8
    19
      Crypto/src/ROT13.java

+ 8
- 19
Crypto/src/ROT13.java View File

@@ -1,24 +1,14 @@
1
-import java.util.*;
2
-
3 1
 public class ROT13  {
4
-    private int shift;
5
-    private Map<Character, Character> cypher = new HashMap<>();
2
+    private String cryptKey;
3
+    private String alphabet = "abcdefghijklmnopqrstuvwxyz";
4
+
6 5
 
7 6
     ROT13(Character cs, Character cf) {
8
-        shift = Math.abs((int)cs - (int)cf);
9
-        setupHM();
7
+        int index = Math.abs((int)cs - (int)cf);
8
+        cryptKey = rotate(alphabet, alphabet.charAt(index));
10 9
     }
11 10
 
12
-    ROT13(){}
13
-
14
-    public void setupHM() {
15
-        String alphabet = "abcdefghijklmnopqrstuvwxyz";
16
-
17
-        for(Character c : alphabet.toCharArray()) {
18
-            int offset = (int)c + shift > 122 ? (int)c - shift : (int)c  + shift;
19
-            cypher.put(c, (char)offset);
20
-        }
21
-    }
11
+    ROT13(){ cryptKey = rotate(alphabet, 'n'); }
22 12
 
23 13
     public String crypt(String text) throws UnsupportedOperationException {
24 14
         StringBuilder result = new StringBuilder();
@@ -26,9 +16,9 @@ public class ROT13  {
26 16
         for(Character c : text.toCharArray()) {
27 17
             if (Character.isLetter(c)) {
28 18
                 if (Character.isUpperCase(c)) {
29
-                    result.append(Character.toUpperCase(cypher.get(Character.toLowerCase(c))));
19
+                    result.append(Character.toUpperCase(cryptKey.charAt(alphabet.indexOf(Character.toLowerCase(c)))));
30 20
                 }
31
-                else result.append(cypher.get(c));
21
+                else result.append(cryptKey.charAt(alphabet.indexOf(c)));
32 22
             }
33 23
             else result.append(c);
34 24
         }
@@ -46,5 +36,4 @@ public class ROT13  {
46 36
     public static String rotate(String s, Character c) {
47 37
         return s.substring(s.indexOf(c)) + s.substring(0, s.indexOf(c));
48 38
     }
49
-
50 39
 }